Question

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sereen.sql.Info;
import sereen.sql.InfoServicesNew;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class PenddingOrders extends Activity {
ArrayList<Info> info=new ArrayList<Info>(); 

    int imgPendding=R.drawable.ex2;
    ListView list;
    ProgressDialog pd;
    ArrayAdapter<String> adapter;
    private String defValue = "N/A";

    InfoServicesNew databaseHelper;
     String name=InfoServicesNew.DB_TABLE_NAME;
    static int img[]={R.drawable.ex2,R.drawable.ex2,R.drawable.ex2,R.drawable.ex2,
        R.drawable.ex2,R.drawable.ex2,R.drawable.ex2,R.drawable.ex2, R.drawable.ex2,
        R.drawable.ex2};
    String data;
    Intent o;
    int position;
    Object object;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pendding_orders);

        databaseHelper = new InfoServicesNew(this);



        list=(ListView)findViewById(R.id.listView1);
        pd = new ProgressDialog(this);

        new asy().execute("http://jsonblob.com/api/jsonBlob/53021f22e4b0f9ce1677329a");






    } 


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pendding_orders, menu);
        return true;
    }
    public class asy extends AsyncTask<String, String, ArrayList<Info>>
    {



        @Override
        protected ArrayList<Info> doInBackground(String... params) {
            // TODO Auto-generated method stub

             //activity is defined as a global variable in your AsyncTask

            try {

                HttpClient hc = new DefaultHttpClient();
                HttpGet hg = new HttpGet(params[0]);
                HttpResponse hr = hc.execute(hg);
                HttpEntity he = hr.getEntity();
                data = EntityUtils.toString(he);
                Log.i("data", data);

            } 
            catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            ArrayList<Info> sereenlist = new ArrayList<Info>();
            sereenlist = getJSONData(data);

            return sereenlist;



        }


        private ArrayList<Info> getJSONData(String data) {
            // TODO Auto-generated method stub



            ArrayList<Info> rs = null;


                try {

                JSONObject obj = new JSONObject(data);
                JSONArray finalObj = obj.optJSONArray("orders");

                for (int i = 0; i < finalObj.length(); i++) 
                {

                    final String orderNumber = finalObj.optJSONObject(i).optString(
                            "order-number");
                    final String orderAmount = finalObj.optJSONObject(i).optString(
                            "order-amount");
                    final String date = finalObj.optJSONObject(i).optString(
                            "date");
                    final String client = finalObj.optJSONObject(i).optString(
                            "client");
                    final String upperLimit = finalObj.optJSONObject(i).optString(
                            "upper-limit");
                    final String debt = finalObj.optJSONObject(i).optString(
                            "debt");



                    long id1=databaseHelper.insert(new Info(client,orderAmount,date ,orderNumber,upperLimit,debt));
                //  long id1 = databaseHelper.insert(info);

                    if(id1 < 0)
                    {
                        Toast.makeText(getApplicationContext(), "unsuccessfull add", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
                    }


                    // select all



                }


                  rs = databaseHelper.selectAll();

                    databaseHelper.close();
                    Log.i("size", finalObj.length()+"");
            }//try end

            catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
                return rs;
        }



        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd.setTitle("fetching");
            pd.setMessage("waiting...");
            pd.show();
        }



        @Override
        protected void onPostExecute(ArrayList<Info> result) {
            // TODO Auto-generated method stub


            SetAdapterList(result);

            pd.dismiss();
        }


        private void SetAdapterList(ArrayList<Info> result) 
        {
            // TODO Auto-generated method stu

 CustomAdapter adapter=new CustomAdapter(getApplicationContext(),result);
            list.setAdapter(adapter);
//          

        }

        }

}

strong text what i want to do is to get all the JSON data from the link .. and it show in the logcat so i get it successfully .. and then i try to insert it in the database using dbhelper and info class which contain getter and setter for all values .. but each time i run the code here what i get :

02-19 01:09:34.490: E/AndroidRuntime(1210): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Était-ce utile?

La solution 5

i found out the problem .. it was because of the toast ... we can't make a toast inside doInBackground service .. my code worked just fine ..

Autres conseils

You're calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example

activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
  }
});

First of all you have to get the JSON Data from network and store them in a structure. So, the first step will be something like that . For json parsing i used Gson library. You have also to create a model class for your objects that you will receive from the requests.

private void getJSONModelHttpRequest(){
    AsyncHttpClient asyncClient = new AsyncHttpClient();
    asyncClient.get(YOUR_URL_HERE   , new AsyncHttpResponseHandler(){
        @Override
        public void onStart(){ 
        }

        @Override 
        public void onSuccess(String response){

            try {

                JSONObject jsonObj  = new JSONObject(response);
                Gson gson = new Gson();
                ModelClass model = gson.fromJson(jsonObj.toString() , ModelClass.class);
                // store the models in a array list or something like that to have the data available in the future
                Log.d(“Model”, " model = " +teamModel.getAnAtttributeVal);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onFailure(Throwable e,String response){

        }

        @Override
        public void onFinish(){
            // Your database insertions here
            }
    });
}

You can also call the Toast using handler itself, provided you use the handler's message passing feature.

What we do is pass the message which is your string using sendMessage() method inside your Thread,

handler.sendMessage(msgObj);

and tehn get the message inside the handler's handleMessage(Message msg) method using,

String aResponse = msg.getData().getString("message");

Complete example here.

in your code do it like this .first create a handler and send data to handler whatever you want to show

  if(id1 < 0)
                    {
                     Message msg=new Message();
                  msg.obj=unsuccessfull add;
                     handle.sendMessage(msg);

                    }

Handler handle=new Handler(){

    public void handleMessage(Message msg) {
  String data=(String)msg.obj;
 Toast.makeText(activity, data, Toast.LENGTH_SHORT).show();

        }


};      
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top