AutoCompleteTextView & Async class - java

I am a rookie in the Android world and I built up a small training SW based on the 2.1 Google API.
At that time I did not know yet about main thread and worker threads, so I put all my code in the main thread.
Since, I fixed it with async classes for my netwkork access to fit the 4.0 Google API.
Ok, but one last thing bothers me and I just can not find any clues.
It is about an AutoCompleteTextView on a field ville ("town" in french).
BEFORE (2.1):
public void onTextChanged(CharSequence s, int start, int before, int count)
{
String result = null;
InputStream is = null;
List<String> r = new ArrayList<String>();
if (ville.enoughToFilter())
{
is = connexionHttp(BASE_URL + "ville.php?ville=" + ville.getText());
result = lectureData(is);
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("VILLE"));
a_idVil.add(json_data.getString("CLEF_VILLE"));
}
ville.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_selectable_list_item,r));
ville.setOnItemSelectedListener(new villeListener());
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
Log.d("***** TestActivity/onTextChanged: JSONException *****", "--"+e1.toString()+"--");
}
catch(ParseException e1)
{
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
Log.d("***** TestActivity/onTextChanged: ParseException *****", "--"+e1.toString()+"--");
}
}
}
public class villeListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row)
{
villePosition = pos;
}
public void onNothingSelected(AdapterView<?> arg0) { }
}
runs 100% perfect:
-> after the 4th caracters, the query runs on MySql to find all the towns beginning with the 4 given letters, and displays the selection list to select the right one: OK
-> the listener give the index of the choosen town: OK
AFTER (4.0)
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (ville.enoughToFilter())
{
new RemplirVille().execute(BASE_URL + "ville.php?ville=" + ville.getText());
Log.d("***********","AVANT");
ville.setOnItemSelectedListener(new villeListener());
Log.d("***********","APRES");
}
}
public class villeListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row)
{
villePosition = pos;
Log.d("*************9999999", "1111111111");
}
public void onNothingSelected(AdapterView<?> arg0) { }
}
class RemplirVille extends AsyncTask<String, String, List<String>>
{
Integer errorMsgId;
String errorMsgParam;
protected List<String> doInBackground(String... param)
{
List<String> listeAffichageVille = new ArrayList<String>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(param[0]);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() < 400)
{
HttpEntity entity = response.getEntity();
String entityStr = EntityUtils.toString(entity);
JSONArray json_array = new JSONArray(entityStr);
for(int i=0;i<json_array.length();i++)
{
JSONObject json_ligne = json_array.getJSONObject(i);
listeAffichageVille.add(json_ligne.getString("VILLE"));
a_idVil.add(json_ligne.getString("CLEF_VILLE"));
}
}
else
{
Log.d("***** TestActivity/ASYNC RemplirVille: EXCEPTION http error *****", "--"+response.getStatusLine().toString()+"--");
this.errorMsgId = R.string.http_site_error;
listeAffichageVille = null;
}
}
catch (Exception ex)
{
Log.d("***** TestActivity/ASYNC RemplirVille: EXCEPTION decode error *****", "--"+ex.toString()+"--");
this.errorMsgId = R.string.http_decode_error;
this.errorMsgParam = ex.getLocalizedMessage();
listeAffichageVille = null;
}
return listeAffichageVille;
}
protected void onProgressUpdate(String... item) { }
protected void onPreExecute(List<String> list) { }
protected void onPostExecute(List<String> list)
{
if (list == null)
{
if (this.errorMsgId != null)
{
String msg = TestActivity.this.getString(this.errorMsgId);
Toast.makeText(TestActivity.this,msg,Toast.LENGTH_LONG).show();
}
}
else
{
ville.setAdapter(new ArrayAdapter<String>(TestActivity.this,android.R.layout.simple_selectable_list_item,list));
}
}
}
runs with troubles:
-> you have to put in (enoughToFilter + 1) caractères to diplay the list of the towns: BAD
-> the listener is even not run anymore: BAD
In fact enoughToFilter works well, it launches the RemplirVille class which runs ok except that it does not displays the list!
But, if you put in 1 more caracter:
-> enoughToFilter still working well
-> RemplirVille brings the data one more time.... but this time the selection list displays well.
Any idea about that topic?
I guess it is a context problem, but even with a GetApplicationCOntext I just can not get it.
Thanks.

Calling AutoCompleteTextView.setAdapter() does not automatically show the dropdown, but you can force the dropdown to be shown with AutoCompleteTextView.showDropDown().
protected void onPostExecute(List<String> list){
//...
ville.setAdapter(new ArrayAdapter<String>(TestActivity.this,android.R.layout.simple_selectable_list_item,list));
if(ville.isInputMethodTarget()){
ville.showDropDown();
}
//...
}
Without this, the dropdown was not shown until the next character was typed, which gave the (enoughToFilter + 1) problem.

Related

Parsing OkHttp in android?

textView = findViewById(R.id.textVieww);
String url = "https://zenquotes.io/api/random";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
try {
JSONArray jsonarray = new JSONArray(myResponse);
for(int i=0; i<jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
Quote.this.runOnUiThread(() ->
textView.setText(myResponse));
}
}
});
}
This is the part im stuck on i think im on the right track but not sure where to go from here im trying to get the "q" information from the returned url and the "a" information but it just outputs everything any suggestions?
What was your problem
Even when you parsed JSON string, you were still using the myResponse string in your textView.setText() method.
Continuing your code snippet
your code snippet is quite short, but i do think i can quite understand what you mean.
So let's say that we have Activity, which is called MainActivity and in that activity we have two views, one TextView called that has an id of tv_author_and_quote and one Button which has a xml id btn_request_quote.
The button has an OnClickListener which calls method requestForQuote().
Our onCreate + the variables of Button and TextView looks like this:
TextView tvAuthorAndQuote;
Button btnRequestQuote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvAuthorAndQuote = findViewById(R.id.tv_author_and_quote);
btnRequestQuote = findViewById(R.id.btn_request_quote);
btnRequestQuote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestForQuote();
}
});
}
And then we have a code itself for method requestForQuote():
public void requestForQuote() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = Objects.requireNonNull(response.body()).string();
String myFormattedQuote = "";
try {
JSONArray jsonarray = new JSONArray(myResponse);
for(int i=0; i<jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
String quote = obj.getString("q");
String author = obj.getString("a");
Log.d(TAG, "onResponse: quote:" + quote);
Log.d(TAG, "onResponse: author:" + author);
myFormattedQuote = author + ": " + quote;
}
} catch (JSONException e) {
e.printStackTrace();
}
final String myFinalQuote = myFormattedQuote;
MainActivity.this.runOnUiThread(() -> {
if (!myFinalQuote.equals("")) {
tvAuthorAndQuote.setText(myFinalQuote);
} else {
tvAuthorAndQuote.setText(myResponse);
}
});
}
}
});
}
The code above basically uses your existing solution, but instead of setting the text of textView with myResponse string, it parses the json array and gets a quote and an author from it. Then it just logs it (just for testing purposes), then it constructs the string which gets displayed to the if there is any, otherwise it prints the response. That it is.
Using Gson library
import it into your gradle dependecies
implementation 'com.google.code.gson:gson:2.8.7'
Write short "holder" class called Quote
public class Quote {
public Quote() {
}
String q;
String a;
String h;
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getH() {
return h;
}
public void setH(String h) {
this.h = h;
}
#NonNull
#NotNull
#Override
public String toString() {
return a + ": " + q;
}
}
Then the requestForQuote() method could look something like this:
public void requestForQuoteWithGson() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = Objects.requireNonNull(response.body()).string();
Type listType = new TypeToken<ArrayList<Quote>>(){}.getType();
List<Quote> yourClassList = new Gson().fromJson(myResponse, listType);
if (yourClassList != null && yourClassList.size() > 0) {
final Quote quote = yourClassList.get(0);
if (quote != null) {
myQuotes.add(quote);
MainActivity.this.runOnUiThread(() ->
tvAuthorAndQuote.setText(quote.toString())
);
}
}
}
}
});
}

How to retrieve first and 2nd element of List inside Array in Java?

I'm pretty new to Java, and currently build client program based on Android.
I have backend server written in Python that will produce result containing some List inside Array.
Here is result from python I should get:
[[id, shopName], [id, shopName], ...]
Example:
[[1, Jakarta], [2, Bali], ...]
Basically, I need to have String[] containing id, and String[] containing name, for spinner adapter.
String[] shopServId, shopServName;
List arrayListShopServId, arrayListShopServName;
// in onCreate()
arrayListShopServId = new ArrayList();
arrayListShopServName = new ArrayList();
and on XMLRPCCallback listener onResponse()
Object[] classObjs = (Object[]) result;
int length = classObjs.length;
shopServId = new String[classObjs.length];
shopServName = new String[classObjs.length];
if ( length > 0) {
arrayListShopServId.clear();
arrayListShopServName.clear();
for (int i=0; i<length; i++) {
#SuppressWarnings("unchecked")
Map<String,Object> classObj = (Map<String,Object>)classObjs[i];
arrayListShopServId.add(classObj.get("id"));
arrayListShopServName.add(classObj.get("name"));
// id and name here are object fields key to get by using XMLRPC
shopServId[i] = arrayListShopServId.get(i).toString();
shopServName[i] = arrayListShopServName.get(i).toString();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
loadSpinnerSaleShop();
}
});
} else {
System.out.println("SaleShop not found!");
}
But it gives me an error
java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.util.Map
How can I achieve that?
EDIT
For those who want to know, I use XMLRPC AsynTask.
Full part of the relevant code:
TaskId:
private void readSaleShop() {
readSaleShopTaskId = util.soe_salesman_shops(listener, database, uid, password, "sale.order",
employeeId);
}
The Listener:
XMLRPCCallback listener = new XMLRPCCallback() {
public void onResponse(long id, Object result) {
Looper.prepare();
if(id==readSaleShopTaskId) {
Object[] classObjs = (Object[]) result;
int length = classObjs.length;
shopServId = new String[classObjs.length];
shopServName = new String[classObjs.length];
if ( length > 0) {
arrayListShopServId.clear();
arrayListShopServName.clear();
for (int i=0; i<length; i++) {
#SuppressWarnings("unchecked")
Map<String,Object> classObj = (Map<String,Object>)classObjs[i];
arrayListShopServId.add(classObj.get("id"));
arrayListShopServName.add(classObj.get("name"));
shopServId[i] = arrayListShopServId.get(i).toString();
shopServName[i] = arrayListShopServName.get(i).toString();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
loadSpinnerSaleShop();
}
});
} else {
System.out.println("SaleShop not found!");
}
} else if(id==updateSaleOrderTaskId) {
final Boolean updateResult =(Boolean)result;
if(updateResult)
{
Log.v("SO UPDATE", "successfully");
util.MessageDialog(SOFormActivity.this,
"Update SO succeed.");
}
else{
util.MessageDialog(SOFormActivity.this,
"Update SO failed. Server return was false");
}
} else if (id == createSOTaskId) {
String createResult = result.toString();
if(createResult != null)
{
Log.v("SO CREATE", "successfully");
util.MessageDialog(SOFormActivity.this,
"Create SO succeed. ID = " + createResult);
}
else
{
util.MessageDialog(SOFormActivity.this,
"Create SO failed. Server return was false");
}
}
Looper.loop();
}
public void onError(long id, XMLRPCException error) {
Looper.prepare();
Log.e("SOForm", error.getMessage());
util.MessageDialog(SOFormActivity.this, error.getMessage());
Looper.loop();
}
public void onServerError(long id, XMLRPCServerException error) {
Looper.prepare();
Log.e("SOForm", error.getMessage());
util.MessageDialog(SOFormActivity.this, error.getMessage());
Looper.loop();
}
};
method I use from UtilAsync class:
public long soe_salesman_shops(XMLRPCCallback listener, String db, String uid, String password,
String object, String employeeId) {
long id = client.callAsync(listener, "execute", db, Integer.parseInt(uid), password, object,
"soe_salesman_shops", Integer.parseInt(employeeId));
return id;
}
classObjs[i] is a an object array. What you can do is cast it to an Array and then get the required data:
Object[] classObj = (Object[])classObjs[i];
arrayListShopServId.add(classObj[0]);
arrayListShopServName.add(classObj[1]);
Your result is a Object[][], so you can do
classObj.put(classObjs[i][0], classObjs[i][1]);
But you can directly do
arrayListShopServId.add(classObjs[i][0]);
arrayListShopServName.add(classObjs[i][1]);
This is a normal behavior.
You have :
Object[] classObjs = (Object[]) result;
Map<String,Object> classObj = (Map<String,Object>)classObjs[i];
You're trying to cast an Object[] element (classObjs[i]) to a different type (Map).
You have to construct the element of the classObj Map in a proper way.
I've ended up changing my python code so it will produce result List of Python Dictionary like this
[{'id':id, 'name':name}, {'id':id, 'name':name}, ...}]
So my code is working now.
But still confuse how to get certain element from List inside List.
So, if someone have working solution, I'll mark that as an answer.

Getting null object reference If i start 2nd activity before 3rd activity (No error if I move from 1st to 3rd directly)

I know its a common error , and i know lots of topics here were asking about the same error, but i tried alot of solutions and non works.
My application is like this:
1st activity is a sign in activity,
2nd is a menu to navigate where to go,
3rd is the customer's details.
I think i know where the problem is but i don't whats causing it
In the 2nd activity i am calling a function to get the customer id (the same function i am calling in the 3rd activity but without taking all the details i am only taking it's ID because i need it in other activities )
So result i am getting second time is always null , which is causing this error
so if i jump directly from 1st to 3rd app doesn't crash.
but (1st 2nd 3rd ) then the function will be called twice (even though i am storing data in a different object) and works only at the first time it's called
Hope i explained it well
now my code for 2nd activity:
public class AfterLogin extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncpkAbone().execute(SharedValues.AboneKod);
setContentView(R.layout.activity_after_login);
}
public void AboneBilgiPressed(View v){
Intent i = new Intent(AfterLogin.this, UserDetailsActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
protected class AsyncpkAbone extends AsyncTask<String,Void,UserDetailsTable>
{
#Override
protected UserDetailsTable doInBackground(String... params) {
// TODO Auto-generated method stub
UserDetailsTable userDetail2=null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetUserDetails(params[0]);
JSONParser parser = new JSONParser();
userDetail2 = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail2;
}
#Override
protected void onPostExecute(UserDetailsTable result2) {
// TODO Auto-generated method stub
SharedValues.AboneKod =result2.getAboneKod();
SharedValues.pkAbone = result2.getPkAbone();
}
}
the Code for the 3rd activity (user details)
public class UserDetailsActivity extends AppCompatActivity {
TextView tvAdres, tvTelefon,tvpkAbone;
String Adres;
String WEBParola;
String Tel1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
new AsyncUserDetails().execute(SharedValues.AboneKod);
tvAdres = (TextView) findViewById(R.id.tv_firstname);
tvAdres.setTextIsSelectable(true);
tvTelefon = (TextView) findViewById(R.id.tv_lastname);
tvTelefon.setTextIsSelectable(true);
tvpkAbone = (TextView) findViewById(R.id.tv_pkAbone);
tvpkAbone.setTextIsSelectable(true);
tvAdres.setText(Adres);
tvTelefon.setText(Tel1);
tvpkAbone.setText(String.valueOf( SharedValues.pkAbone));
}
protected class AsyncUserDetails extends AsyncTask<String,Void,UserDetailsTable>
{
#Override
protected UserDetailsTable doInBackground(String... params) {
// TODO Auto-generated method stub
UserDetailsTable userDetail=null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetUserDetails(params[0]);
JSONParser parser = new JSONParser();
userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail;
}
#Override
protected void onPostExecute(UserDetailsTable result) {
// TODO Auto-generated method stub
tvAdres.setText(result.getAdres());
tvTelefon.setText(result.getTelefon());
}
}
the data i get from the function is stored in a object of type (userdetails tables)
the code for the Userdetailstable is (might be needed)
package com.artyazilim.art;
public class UserDetailsTable {
String Adres,Tel1,AboneKod,WEBParola;
int pkAbone;
public UserDetailsTable(String Adres, String Tel1, String AboneKod,
String WEBParola,int pkAbone) {
super();
this.Adres = Adres;
this.Tel1 = Tel1;
this.AboneKod = AboneKod;
this.WEBParola = WEBParola;
this.pkAbone = pkAbone;
}
public UserDetailsTable() {
super();
this.Adres = null;
this.Tel1 = null;
this.AboneKod = null;
this.WEBParola = null;
this.pkAbone = 0;
}
public String getAdres() {
return Adres;
}
public void setAdres(String adres) {
Adres = adres;
}
public String getTelefon() {
return Tel1;
}
public void setTelefon(String telefon) {
Tel1 = telefon;
}
public String getAboneKod() {
return AboneKod;
}
public void setAboneKod(String aboneKod) {
AboneKod = aboneKod;
}
public String getWEBParola() {
return WEBParola;
}
public void setWEBParola(String WEBParola) {
this.WEBParola = WEBParola;
}
public int getPkAbone() {
return pkAbone;
}
public void setPkAbone(int pkAbone) {
this.pkAbone = pkAbone;
}
}
the function which i am calling in the both Async is this:
public JSONObject GetUserDetails(String AboneKod) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","Service1");
o.put("method", "GetUserDetails");
p.put("AboneKod",mapObject(AboneKod));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
and in the web service this is the GetUserDetails function:
public DataTable GetUserDetails(string AboneKod)
{
DataTable userDetailsTable = new DataTable();
userDetailsTable.Columns.Add(new DataColumn("Adres", typeof(String)));
userDetailsTable.Columns.Add(new DataColumn("Tel1", typeof(String)));
userDetailsTable.Columns.Add(new DataColumn("pkAbone", typeof(String)));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT Adres,Tel1,pkAbone FROM r_Abone WHERE AboneKod='" + AboneKod + "';";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
userDetailsTable.Rows.Add(reader["Adres"], reader["Tel1"], reader["pkAbone"]);
}
}
reader.Close();
dbConnection.Close();
return userDetailsTable;
}
the error i am getting when going from 2nd to 3rd is
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.artyazilim.art.UserDetailsTable.getAdres()' on a
null object reference
10-30 05:33:13.410 24881-24881/com.artyazilim.art E/AndroidRuntime:
at
com.artyazilim.art.UserDetailsActivity$AsyncUserDetails.onPostExecute(UserDetailsActivity.java:74)
10-30 05:33:13.410 24881-24881/com.artyazilim.art E/AndroidRuntime:
at
com.artyazilim.art.UserDetailsActivity$AsyncUserDetails.onPostExecute(UserDetailsActivity.java:47)
10
i know it seems like a duplicate and I know the rules search before ask,I have spent lots of time trying other's solutions but the reason i might didn't find the answer else where is because i don't know whats is actually causing this error so not knowing what to search for.
thanks in advance :)
In you second activity check if result2.getAboneKod(); is not returning a null object.
I think this is why when you open the 3rd activity from the 2nd, you have the NullPointerException.

How to convert from a List to Array ? Android

okay guys, here is the thing, I have one application consuming ODATA service, in SMP server, I'm getting this Data like this:
public class callService extends AsyncTask<Void, Void, ArrayList<String>>
{
public ArrayList<String> doInBackground(Void... params)
{
ODataConsumer c = ODataJerseyConsumer.create("http://MyUrlService:8080");
List<OEntity> listEntities = c.getEntities("MYENTITYTOCONSUME").execute().toList();
System.out.println("Size" + listEntities.size());
if (listEntities.size() > 0)
{
for (OEntity entity : listEntities)
{
zmob_kunnr.add((String) entity.getProperty("Name1").getValue()
+ " - "
+ entity.getProperty("Kunnr").getValue().toString());
}
}
return zmob_kunnr;
}
protected void onPostExecute(ArrayList<String> result)
{
super.onPostExecute(result);
adapter = new ArrayAdapter<String>(ConsumoKnuur.this, android.R.layout.simple_list_item_1, result);
list.setAdapter(adapter);
}
}
Okay I got this solution from web and could implement as list, and I need to store this entity which one is a List of customers and get the two attributes from this entity and save in my database so:
Entity Customer:Custormer_ID, Customer_Name
Here is my code to call my sqlite:
public void sqlite()
{
sql_obj.open();
sql_obj.deleteAll();
for(int i=0; i < zmob_kunnr.size(); i++)
{
sql_obj.insert(zmob_kunnr.get(i).toString(), zmob_kunnr.get(i).toString() );
}
sql_obj.close();
}
And my SQLite:
private static final String TABLE_CLIENTE = "CREATE TABLE "
+ TB_CLIENTE
+ "(ID_CLIENTE INTEGER PRIMARY KEY AUTOINCREMENT, " //Id for controller my logics
+ " Kunnr TEXT , " //customer ID
+ " Name1 TEXT );"; //customer_name
public long insert(String name1, String Kunnr)
{
ContentValues initialValues = new ContentValues();
initialValues.put("Name1", Name1); //Customer_Name
initialValues.put("Kunnr", Kunnr); //Customer_ID
return database.insert(TB_CLIENTE, null, initialValues);
}
And off course my other methods, that is not important, so whats happening when I run my "for" in the sql call method, I get the size() of the list and the rows of the list and store the entire row in the one column of the database each time, so I got two different tables with the same values,
how can I change solve this problem instead of consume in list I need to consume in array ? or I need to create a method that get the list values and after a ,(coma) , create two differents objects to store these data ??
I took a long look in the internet and didn't find nothing, probably it's because i don't know yet, how so, I don't know for what I'm looking for it, I'm using the odata4j API and here is the link of the documentation, http://odata4j.org/v/0.7/javadoc/
I'm new on programming, so I'm really in trouble with this, any suggestions any helps will be truly, appreciate,
Thanks a lot and have a nice day !!!
You can add each entity to the `ArrayList' array by doing the following:
for (OEntity entity : listEntities) {
zmob_kunnr.add(entity);
}
This will allow you to access the data contained in the entity via getProperty() when inserted into the database.
The following statement is also not needed, as the for each loop runs through every element in the list, thus for (OEntity entity : listEntities) will not execute if the list is empty.
if (listEntities.size() > 0) {
...
}
If you have multiple ODataConsumers, you have two choices, depending on your requirements (if I understand you question correctly):
You can sequentially get each ODataConsumer, get the listEntities, and add it to the zmob_kunnr list, and after the list items are added to the database, clear the zmob_kunnr list, and call doInBackground with a new URL. This is what your current solution allows.
It appears to need to know which property is associated with a URL when reading the values into the DB. You can use a POJO as a holder for the entity and its list of properties. You can now add and remove properties. Note that properties will be removed in the same order they where inserted.
public class OEntityHolder {
private final OEntity entity;
private Queue<String> properties;
public OEntityHolder(OEntity entity) {
this.entity = entity;
this.properties = new LinkedBlockingQueue<>();
}
public OEntity getEntity() {
return this.entity;
}
public void addProperty(String property) {
this.properties.add(property);
}
public void removeProperty() {
this.properties.poll();
}
}
This will require a change to the list holding the entities:
ArrayList<OEntityHolder> zmob_entity_holders = new ArrayList<>();
If you would like to add all the entities from the different URLs at the same time, you will need to have access to all the URLs when doInBackground is called. Something like this:
public ArrayList<OEntityHolder> doInBackground(Void... params) {
String [][] urls = {{"http:MyUrl/ZMOB_FECODSet", "Name1", "Fecod"},
{"http:MyUrl/ZMOB_OTEILSet", "Name2", "Oteil"},
{"http:MyUrl/ZMOB_KUNNRSet", "Name3", "Kunnr"},
{"http:MyUrl/ZMOB_BAULTSet", "Name4", "Bault"}};
for (String [] urlProp:urls) {
//Here you get the list of entities from the url
List<OEntity> listEntities = ODataJerseyConsumer.create(urlProp[0]).getEntities("MYENTITYTOCONSUME").execute().toList();
for (OEntity entity:listEntities) {
OEntityHolder holder = new OEntityHolder(entity);
for (int i = 1; i < urlProp.length; i++)
holder.addProperty(urlProp[i]);
zmob_entity_holders.add(holder);
}
}
//At this point, all of the entities associated with the list of URLS will be added to the list
return zmob_entity_holders;
}
You now have ALL of the entities associated with the list of URLs in zmob_kunnr. Before you can and can insert then into the DB like so:
for (OEntityHolder holder : zmob_entity_holders) {
sql_obj.insert(holder.getEntity().getProperty(holder.removeProperty()).toString(), holder.getEntity().getProperty(holder.removeProperty()).toString());
}
If each entity has a associated name, you can store the names in a map, where the key is the URL and the value the name.
HashMap<String, String> urlEntityNames = new HashMap<>();
urlEntityNames.put("http://MyUrlService:8080", "MYENTITYTOCONSUME");
...//Add more URLs and entity names
You can then, when running through the list of entities, do a look-up in the map to find the correct name:
List<OEntity> listEntities = ODataJerseyConsumer.create(url).getEntities(urlEntityNames.get(url)).execute().toList();
I hope this helps, if I misunderstood you just correct me in the comments.
EDIT: Added list of URLs, holder and DB insert.
I guess i found a solution, but my log cat, is giving an exception to me any updtades about my 2nd doInBackgroundBault (Material),
public class callServiceCliente extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressC = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Clientes", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer ccli = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesKunnr = ccli.getEntities("ZMOB_KUNNRSet").execute().toList();
System.out.println("Size" + listEntitiesKunnr.size());
for (OEntity entityKunnr : listEntitiesKunnr) {
zmob_kunnr.add(entityKunnr);
}
return zmob_kunnr;
}
protected void onPostExecute(ArrayList<OEntity> kunnr) {
super.onPostExecute(kunnr);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int k = 0; k < zmob_kunnr.size(); k++) {
sql_obj.insertCliente(zmob_kunnr.get(k).getProperty("Kunnr").getValue().toString().toUpperCase(), zmob_kunnr.get(k).getProperty("Name1").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
clienteAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, kunnr);
listCliente.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressC.dismiss();
new callServiceMaterial().execute();
}
}
public class callServiceMaterial extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressM = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Materiais", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer cmat = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList();
System.out.println("Size" + listEntitiesBault.size());
for (OEntity entityBault : listEntitiesBault) {
zmob_bault.add(entityBault);
}
return zmob_bault;
}
protected void onPostExecute(ArrayList<OEntity> bault) {
super.onPostExecute(bault);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int b = 0; b < zmob_bault.size(); b++) {
sql_obj.insertMaterial(zmob_bault.get(b).getProperty("Matnr").getValue().toString().toUpperCase(), zmob_bault.get(b).getProperty("Maktxt").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
materialAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, bault);
listMaterial.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressM.dismiss();
new callServiceProblema().execute();
}
}
public class callServiceProblema extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressProb = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Problemas", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer cprob = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesFecod = cprob.getEntities("ZMOB_FECODSet").execute().toList();
System.out.println("Size" + listEntitiesFecod.size());
for (OEntity entityFecod : listEntitiesFecod) {
zmob_fecod.add(entityFecod);
}
return zmob_fecod;
}
protected void onPostExecute(ArrayList<OEntity> fecod) {
super.onPostExecute(fecod);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int f = 0; f < zmob_fecod.size(); f++) {
sql_obj.insertProblema(zmob_fecod.get(f).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_fecod.get(f).getProperty("Kurztext").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
problemaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, fecod);
listProblema.setAdapter(problemaAdapter);
} catch (Exception eq) {
}
progressProb.dismiss();
new callServiceProcedencia().execute();
}
}
public class callServiceProcedencia extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressProc = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando base de dados", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer c = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesProcedencia = c.getEntities("ZMOB_OTEILSet").execute().toList();
System.out.println("Size" + listEntitiesProcedencia.size());
for (OEntity entityProcedencia : listEntitiesProcedencia) {
zmob_oteil.add(entityProcedencia);
}
return zmob_oteil;
}
protected void onPostExecute(ArrayList<OEntity> oteil) {
super.onPostExecute(oteil);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int o = 0; o < zmob_oteil.size(); o++) {
sql_obj.insertCliente(zmob_oteil.get(o).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_oteil.get(o).getProperty("Kurztext").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
procedenciaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, oteil);
// listCliente.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressProc.show(Atualizar_Dados.this, "Finalizado", "Base de dados atualizada", true, true).dismiss();
Toast.makeText(Atualizar_Dados.this, "Base de dados atualizada com sucesso", Toast.LENGTH_LONG).show();
}
}
Okay, so here is the solution that i find, and i couldn't insert your solution because, when i put inser.add(entity), they didn't show me the properties but if you have a better way to do what i did, i will really appreciate,
and by the way i need to query this consume by range date in the filter(). like i did here...
List listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList(); but isn't working, so i don't have any ideas why, i saw couple close solution on the internet and saw fields like .top(1) and .first(); that i didn't understand...
thanks a lot !!!

Multiple upload photo using LoopJ AndroidAsyncHttp

I'm going to upload multiple photo/video using LoopJ AndroidAsyncHttp to server. My problem is i need to add cancel button for each of the photo and allow the user to cancel the uploading. May i know anyone got the solution for this? or any others better example for me to refer?
My Code as below :-
public static void putMultipleUploadPhoto(String server,
final ProgressBar progressbarb, final String FileType, final TextView textviewb, final String FolderPath, final int itemcount, final int position)
{
final String url = "http://" + server + ":" + server.Photo_Upload;
File myFile = new File(data);
final RequestParams params = new RequestParams();
try {
params.put("data", myFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final AsyncHttpClient client = new AsyncHttpClient();
final int totalprogress1 = 0;
try {
client.post(url,params,new AsyncHttpResponseHandler() {
public void onStart() {
// Initiated the request
progressbarb.setProgress(0);
}
#Override
public void onProgress(int position, int length) {
// TODO Auto-generated method stub
int totalprogress;
totalprogress = (position*100)/length;
progressbarb.setProgress(totalprogress);
super.onProgress(position, length);
}
#Override
public void onSuccess(String response) {
String regex = "\n"; // Only this line is changed.
String split[] = response.split(regex, 2);
if (split[0] != null)
{
String status[]=split[0].split("\\t");
if (status[0].equals("true"))
{
textviewb.setVisibility(View.VISIBLE);
textviewb.setText("Success");
if (status[0].equals("false"))
{
textviewb.setText("Fail";
textviewb.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onFailure(Throwable e, String response) {
textviewb.setVisibility(View.VISIBLE);
textviewb.setText("Fail");
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Very simple dear-
1)just send one by one image on server and then create a popup window for send next image or cancel.
2)In your database or where you have images just set flag 0 and 1. So you can easily make query
for send image on server which one is pending.
3)And when you got successes response from server change your flag value in database.

Categories

Resources