I've created a method that shall return a two-dimensional Array, everything works perfectly as the array is being correctly filled in the method's try.
But once I display the array on onCreate(), it's returning null.
public class ListTickets extends AppCompatActivity {
public String[][] ticketTab ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
DisplayArray(getTicketsHTTP());
}
private String[][] getTicketsHTTP() {
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
statutTicket = oneTicket.getString("12");
idTicket = oneTicket.getString("2");
} catch (JSONException e) {
Log.e("Err", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket, dateEchanceTicket);
ticketTab[i][5] = String.valueOf(ticketEnretard);
ticketTab[i][6] = statutTicket;
ticketTab[i][7] = idTicket;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
return ticketTab;
}
}
I declared ticketTab outside the onCreate because when I declare it inside the method, I cannot change it inside the try.
How can I return the array correctly?
In your onCreate you are using this line:
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
and those values, nbTicket and nbTicketTab are not declared anywhere in your code, maybe that's why they are returning null, you have to initialize them and asign values.
Related
My scenario is, I have 4 test methods in a test class which are dependent on each other. Out of which two need test data from excel .
I tried #factory with data provider but it is running each test method multiple times.
But I want a sequence to be finished and then next sequence with next set of data from excel should start.
**ExcelUtils.class**
public static Object[][] getTableArray(String FilePath, String
SheetName) throws Exception {
FileInputStream file = null;
try {
file = new FileInputStream(FilePath);
}catch(FileNotFoundException fe){
fe.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
}catch(InvalidFormatException ie) {
ie.printStackTrace();
}catch(IOException io) {
io.printStackTrace();
}
sheet = book.getSheet(SheetName);
Object[][] data = new Object[sheet.getLastRowNum()]
[sheet.getRow(0).getLastCellNum()];
for(int i=0; i<sheet.getLastRowNum();i++) {
for(int k=0; k<sheet.getRow(0).getLastCellNum();k++) {
data[i][k] =
sheet.getRow(i+1).getCell(k).toString();
}
}
return data;
}
**FactoryUtility.class**
#DataProvider(name = "AndB")
public Object[][] getAndB() throws Exception{
Object[][] AnBObjArray = ExcelUtils.getTableArray("Excel
path","sheetName");
return AnBObjArray ;
}
**CreateTest.class**
#Factory(dataProvider="AndB" , dataProviderClass =
FactoryUtility.class)
public CreateTest(String A, String B) {
this.A= A;
this.B= B;
}
#Test(alwaysRun = true, priority=1)
public void Login() {
System.out.println("login");
}
#Test(alwaysRun = true, priority=2)
public void Login() {
System.out.println(A);
}
#Test(alwaysRun = true, priority=3)
public void Login() {
System.out.println(B);
}
#Test(alwaysRun = true, priority=4)
public void Logout() {
System.out.println("Logout");
}
I am not able to pass the data from API json to my textview respectively
I am getting "org.json.JSONObject cannot be converted to JSONArray" error
ERRORS :
W/System.err: org.json.JSONException: Value {"message":"accurate","cod":"200","count":1,"list":[{"id":1252948,"name":"Warangal","coord":{"lat":18,"lon":79.5833},"main":{"temp":315.66,"feels_like":314.6,"temp_min":315.66,"temp_max":315.66,"pressure":1002,"humidity":16,"sea_level":1002,"grnd_level":975},"dt":1590404957,"wind":{"speed":2.13,"deg":129},"sys":{"country":"IN"},"rain":null,"snow":null,"clouds":{"all":53},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]}]}
of type org.json.JSONObject cannot be converted to JSONArray
W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
This is my MainActivity code :
public class MainActivity extends AppCompatActivity {
TextView temp, sunraise, sunsets, wind, pressure, visibility, humidity;
EditText search;
ConstraintLayout constraintLayout;
ImageButton search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temp = findViewById(R.id.temp);
sunraise = findViewById(R.id.sunrise);
sunsets = findViewById(R.id.sunset);
wind = findViewById(R.id.wind);
pressure = findViewById(R.id.pressure);
visibility = findViewById(R.id.visibility);
humidity = findViewById(R.id.humidity);
search = findViewById(R.id.your_city);
constraintLayout = findViewById(R.id.constraintLayout);
search_btn = findViewById(R.id.search_btn);
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager ConnectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
assert ConnectionManager != null;
NetworkInfo networkInfo = ConnectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new WeatherData().execute();
} else {
Snackbar snackbar = Snackbar.make(constraintLayout, "check your Internet connection", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
});
}
class WeatherData extends AsyncTask<String, Void, String> {
String City = search.getText().toString();
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://community-open-weather-map.p.rapidapi.com/find?type=link%252C%20accurate&units=imperial%252C%20metric&q=warangal")
.get()
.addHeader("x-rapidapi-host", "community-open-weather-map.p.rapidapi.com")
.addHeader("x-rapidapi-key", "a65ed4164bmshecc6a41b1453609p12d370jsn36dc92fffc6d")
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONArray jsonObject = new JSONArray(s);
if (jsonObject.length() > 0) {
JSONArray list = jsonObject.getJSONArray(Integer.parseInt("list"));
JSONObject o = list.getJSONObject(Integer.parseInt("0"));
JSONObject main = o.getJSONObject("main");
String temperature = main.getString("temp");
String press = main.getString("pressure");
temp.setText(temperature);
pressure.setText(press);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
This is my JSON :
{
"message":"accurate",
"cod":"200","count":1,
"list":
[{
"id":1252948,
"name":"Warangal",
"coord":
{
"lat":18,
"lon":79.5833
},
"main":
{
"temp":317.1,
"feels_like":316.2,
"temp_min":317.1,
"temp_max":317.1,
"pressure":1003,
"humidity":15,
"sea_level":1003,
"grnd_level":976
},
"dt":1590397763,
"wind":
{
"speed":1.96,
"deg":117
},
"sys":
{
"country":"IN"
},
"rain":null,
"snow":null,
"clouds":{"all":36
},
"weather":
[{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03d"
}]
}]
}
I am just testing to display the json output into my respective textview.After my code is succesfull i will functionalize the search field to get data from API.
Can anyone help me out from this error !
Thank you !
First check if its a json array or json object before assigning if (json instanceof JSONObject)
Any why are you parsing string to integer?
I had been developing and testing on the Codename One simulator and everything worked fine.
However, when I tested it on a real Android device, I get a 405 Method Not Allowed error. This happened on both a POST and GET request.
I suspect it is the #Consume and #Produces which are causing the problem. How do I fix this?
Here are my server side code:
#GET
#Path("/all/{language}")
#Produces("application/json")
public final Response getAllCelebrities(#PathParam("language") String language) {
String celebritiesJSONString = CelebrityActions.getAllCelebritiesNamesJSONString(language);
return Response.ok(celebritiesJSONString).build();
}
#POST
#Path("/login")
#Consumes("application/x-www-form-urlencoded")
#Produces("text/plain")
public final Response login(
#FormParam("loginid") String loginid,
#FormParam("password") String password
) {
System.out.println("login 0 started");
Long fanID;
try {
fanID = AccountsActions.login(loginid, password);
} catch (Exception e) {
return Response.serverError().entity(e.getMessage()).build();
}
if (fanID == null) {
return responseFanIDNotFoundError();
}
System.out.println("This is printed out!!!");
System.out.println("login 100 ended");
return Response.ok().build();
}
And here's my log upon execution of the login() method:
login 0 started
This is printed out!!!
login 100 ended
which means the server side method was ready to return a 200 response.
What is causing the Android client to show a 405 Method Not Allow error?
EDIT: I'm adding my cient-side code here:
(note that this one handles a cookie from a server)
public class Login extends PostConnection {
private final String LoginEndpoint = "account/login";
private String loginIDString;
private String loginPasswordString;
// Tested and works on simulator!
public Login(String loginIDString, String loginPasswordString) {
super();
endpoint = LoginEndpoint;
this.loginIDString = loginIDString;
this.loginPasswordString = loginPasswordString;
}
#Override
protected void prepareParametersMap() {
parametersMap = new HashMap<>();
parametersMap.put("loginid", loginIDString);
parametersMap.put("password", loginPasswordString);
}
}
public abstract class PostConnection extends PostPutConnection {
public PostConnection() {
super();
}
public boolean connect() throws IOException {
connectionRequest.setHttpMethod("POST");
return super.connect();
}
}
public abstract class PostPutConnection extends Connection {
protected HashMap<String, String> parametersMap;
public PostPutConnection() {
super();
}
protected static final void setPostParameters(ConnectionRequest connectionRequest, HashMap<String, String> parametersMap) {
Set<String> paramateterKeys = parametersMap.keySet();
Iterator<String> parameterKeysIterator = paramateterKeys.iterator();
while (parameterKeysIterator.hasNext()) {
String key = parameterKeysIterator.next();
String value = parametersMap.get(key);
connectionRequest.addArgument(key, value);
}
}
protected abstract void prepareParametersMap();
public boolean connect() throws IOException {
prepareParametersMap();
setPost();
setPostParameters();
return super.connect();
}
private void setPostParameters() {
setPostParameters(connectionRequest, parametersMap);
}
private final void setPost() {
connectionRequest.setPost(true);
}
}
public abstract class Connection {
private final static String protocol = "http";
private final static String domain = "192.168.0.109:20000";
protected ConnectionRequest connectionRequest;
protected String endpoint;
public Connection() {
super();
init();
}
protected void init() {
connectionRequest = new ConnectionRequest();
connectionRequest.setCookiesEnabled(true);
ConnectionRequest.setUseNativeCookieStore(true);
}
public boolean connect() throws IOException {
connectionRequest.setUrl(protocol + "://" + domain + "/" + endpoint);
NetworkManager.getInstance().addToQueueAndWait(connectionRequest);
int responseCode = getResponseCode();
return responseCode == 200 ? true : false;
}
private int getResponseCode() {
int responseCode = connectionRequest.getResponseCode();
return responseCode;
}
}
And another method below:
(note that this one does not handle cookies)
public class GetAllCelebrities extends GetConnection {
private final String GetCelebritiesEndpoint = "celebrity/all";
public GetAllCelebrities(String language) {
super();
endpoint = GetCelebritiesEndpoint + "/" + language;
}
}
public abstract class GetConnection extends Connection {
private Map<String, Object> responseData;
public GetConnection() {
super();
}
public boolean connect() throws IOException {
connectionRequest.setHttpMethod("GET");
boolean connectResult = super.connect();
if (!connectResult) {
return false;
}
responseData = getResponseResult();
return true;
}
private Map<String, Object> getResponseResult() throws IOException {
byte[] responseData = connectionRequest.getResponseData();
ByteArrayInputStream responseDataBAIS = new ByteArrayInputStream(responseData);
InputStreamReader responseDataISR = new InputStreamReader(responseDataBAIS, "UTF-8");
JSONParser responseDateJSONParser = new JSONParser();
Map<String, Object> responseResult = responseDateJSONParser.parseJSON(responseDataISR);
return responseResult;
}
public Map<String, Object> getResponseData() {
return responseData;
}
}
And it is called like:
private Map<String, Object> fetchCelebrities() throws IOException {
GetAllCelebrities getAllCelebrities = new GetAllCelebrities("en");
getAllCelebrities.connect();
return getAllCelebrities.getResponseData();
}
private boolean performLogin() throws IOException {
String loginIDString = loginID.getText();
String loginPasswordString = loginPassword.getText();
Login login = new Login(loginIDString, loginPasswordString);
boolean loginResult = login.connect();
return loginResult;
}
It's a bit hard to read all of this code but I'll venture a guess based on the server message. You've set the method to "PUT" along the way in the post put class and that isn't supported by the server yet.
The best way to debug these things is with the network monitor in the Simulator. Its shows the traffic and would have made these things mostly clear
I am using Play 2.0.4 and I'm doing a test unit for actors who make use of the database.
The test begins well, but then at a given moment the connection with the database is closed and the actor who is running fails.
Code:
public class ActorTest extends Helpers {
private FakeApplication app;
private ActorSystem actorSystem;
private ActorRef actorRef;
private BankAccount account;
#Before
public void initTest() {
Map<String, String> params = new HashMap<String, String>();
params.put("db.default.driver", "com.mysql.jdbc.Driver");
params.put("db.default.url", "mysql://root:XXXX#localhost/YYY");
params.put("ebean.default", "models.*");
app = fakeApplication(params);
actorSystem = play.api.libs.concurrent.Akka.system(app.getWrappedApplication());
}
#Test
public void updateAccountTransaction() {
running(app, new Runnable() {
#Override
public void run() {
account = BankAccount.find.byId(new Long(1));
actorRef = actorSystem.actorOf(new Props(new UntypedActorFactory() {
#Override
public UntypedActor create() {
return new AccountTaskActor(account);
}
}));
Calendar fromDate = Calendar.getInstance();
....
....
Calendar toDate = Calendar.getInstance();
final InputRangeDateMessage param = new InputRangeDateMessage(fromDate, toDate);
junit.framework.Assert.assertNotNull(account);
Future<Object> future = Patterns.ask(actorRef, param, 1000000);
Promise<Object> sdf = Akka.asPromise(future);
Promise<Result> r2 = sdf.map(new Function<Object, Result>() {
#Override
public Result apply(Object response) throws Throwable {
if (response instanceof ErrorMessage) {
ErrorMessage e = (ErrorMessage) response;
System.out.println("Error Message " + e.getErrorText());
junit.framework.Assert.assertEquals(e.getErrorCode(), -1);
} else if (response instanceof BankAccountMessage) {
BankAccount a = ((BankAccountMessage) response).getAccount();
System.out.println("BankAccount " + a.accountsLastUpdate);
}
return ok();
}
});
Result test2;
test2 = async(r2);
}
});
}
}
AFAIK, you have to wait for the end of your Promise:
...
Result test2 = r2.get();
I made an android dictionary application. I have created a database named "kamusJawa.sqlite" and copied it to the assets folder. I tried the code in this link Own Database in Assets Folder on Android Eclipse Project
This is my database manager class:
package com.kamusJI;
public class DBHelper extends SQLiteOpenHelper{
private static String DBPATH = "/data/data/com.kamusJI/databases/";
private static String DBNAME = "kamusJawa.sqlite";
private SQLiteDatabase DBSQ;
private final Context KJICtx;
public DBHelper(Context context) throws IOException {
super(context, DBNAME, null, 1);
this.KJICtx = context;
// TODO Auto-generated constructor stub
boolean dbexist = cekDB();
if (dbexist) {
//System.out.println("Database exists");
openDB();
} else {
System.out.println("Database doesn't exist");
createDB();
}
}
public void createDB() throws IOException{
boolean dbExist = cekDB();
if(!dbExist){
this.getReadableDatabase();
try{
salinDB();
}catch (IOException e){
throw new Error("Gagal menyalin database");
}
}
}
boolean cekDB() {
//SQLiteDatabase cekDatabase = null;
boolean cekdb = false;
try{
String path = DBPATH + DBNAME;
File dbfile = new File(path);
//cekDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
cekdb = dbfile.exists();
}catch(SQLException e){
System.out.println("Database tidak ada");
}
return cekdb;
//return cekDatabase !=null ? true : false;
}
private void salinDB() throws IOException{
AssetManager AM = KJICtx.getAssets();
File DbFile = new File(DBPATH+DBNAME);
InputStream in = KJICtx.getAssets().open(DBNAME);
//OutputStream out = new FileOutputStream(DbFile);
OutputStream out = new FileOutputStream("/data/data/com.kamusJI/databases/kamusJawa.sqlite");
DbFile.createNewFile();
byte[] b = new byte[1024];
int i, r;
String[] Files = AM.list("");
Arrays.sort(Files);
i= 1;
String fdb = String.format("kamusJawa.db.00%d", i);
while(Arrays.binarySearch(Files, fdb)>=0){
//InputStream in = AM.open(fdb);
while(( r = in.read(b))>0)
out.write(b,0,r);
in.close();
i++;
fdb = String.format("kamusJawa.db.00%d", i);
}
out.flush();
out.close();
}
public void openDB() throws SQLException{
String path = DBPATH+DBNAME;
DBSQ = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(DBSQ !=null)
DBSQ.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
and this is my main class:
package com.kamusJI;
public class KJI extends ListActivity {
private KJI this_class = this;
String[] Menu = {"Basa Jawa", "Bahasa Indonesia", "Tambah Data"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.Cari, Menu));
ListView lv = getListView();
lv.setTextFilterEnabled(false);
/* Defines On Item Click callback method */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent action = null;
switch(position) {
case 0:
case 1:
action = new Intent(getApplicationContext(), Cari.class);
action.putExtra("MODE", position);
break;
case 2:
action = new Intent(getApplicationContext(), Tambah.class);
action.putExtra("MODE", position);
break;
case 3:
finish();
return;
}
startActivity(action);
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void InitDatabase() {
AsyncTask<String, Void, String> InitDB = new AsyncTask<String, Void, String>() {
Dialog progress = null;
String msg;
DBHelper dbhelper;
#Override
protected void onPreExecute() {
try {
dbhelper = new DBHelper(this_class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!dbhelper.cekDB())
progress = ProgressDialog.show(this_class, "", "Installing Database.\nPlease wait.");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
dbhelper.createDB();
msg = "Database successfully installed.";
} catch (IOException ioe) {
msg = "Database installation failed.";
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progress!=null) {
progress.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
};
InitDB.execute(new String());
}
}
When I run my application, then I go to file explorer, I can't find the data/data/com.kamusJI/databases. How it can be like that?
change your database name extension to .db
You need special permissions like root access to read the path:
/data/data/com.package/databases