English 中文(简体)
• 如何显示json阵列,与AsyncTask进行盘点。
原标题:How to Display json array to listview with AsyncTask?

我是新来的,因此,请让我知道我在哪里错了。

I want convert the jsonarray into custom listview.I tried much but I don t get the solution. I got the value that I want into strValue1(please check the below code ,Activites_Actative.java). Now ,I want to pass this strValue1 into the listview. but I am not able to convert it into listview.

...... 让我知道应该做些什么?

我看一看错误

04-17 12:52:55.795: E/AndroidRuntime(765): FATAL EXCEPTION: AsyncTask #1
04-17 12:52:55.795: E/AndroidRuntime(765): java.lang.RuntimeException: An error occured               while executing doInBackground()
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.lang.Thread.run(Thread.java:1096)
04-17 12:52:55.795: E/AndroidRuntime(765): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.ViewRoot.focusableViewAvailable(ViewRoot.java:1596)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:451)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:451)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:451)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:451)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.View.setFlags(View.java:4474)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.view.View.setFocusableInTouchMode(View.java:3104)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.widget.AdapterView.checkFocus(AdapterView.java:694)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.widget.ListView.setAdapter(ListView.java:437)
04-17 12:52:55.795: E/AndroidRuntime(765):  at com.rahul.cheerfoolz.activites.Activites_Activity$activites.doInBackground(Activites_Actative.java:141)
04-17 12:52:55.795: E/AndroidRuntime(765):  at com.rahul.cheerfoolz.activites.Activites_Activity$activites.doInBackground(Activites_Actative.java:1)
04-17 12:52:55.795: E/AndroidRuntime(765):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-17 12:52:55.795: E/AndroidRuntime(765):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-17 12:52:55.795: E/AndroidRuntime(765):  ... 4 more

感谢。

Activites_Actative.java

public class Activites_Activity extends CheerfoolznativeActivity {

 TextView txtactivity;
 ListView list;
 LazyAdapter adapter;
 ImageView img;
 ProgressBar pgb;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_activites);
    setHeader("Activites");

/*
     list=(ListView)findViewById(R.id.activity_listView);
    adapter=new LazyAdapter(this, mImages,mTitle);
    list.setAdapter(adapter);
*/
    txtactivity = (TextView) findViewById(R.id.activity_textView);
    img=(ImageView)findViewById(R.id.activity_image);
    pgb = (ProgressBar)findViewById(R.id.activity_progressBar);
    new activites().execute();
}

public class activites extends AsyncTask<Void, Void, Void> {
    String parsedString = "
";  
    String strValue1 ;
    public int i=0;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
         pgb.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        String url = " Here my json URL ";

        String strResponse = util.makeWebCall(url);

        try {
            JSONObject objResponse = new JSONObject(strResponse);

            JSONArray jsonnodes = objResponse.getJSONArray(API.cheerfoolz_activities.NODES);
            Log.i(" NO of entries===>" +Activites_Activity.class.getName(),"Number of entries " + jsonnodes.length());

            ArrayList<String> items = new ArrayList<String>();

            for (i = 0; i < jsonnodes.length(); i++) 
            {
                String str = Integer.toString(i); 
                Log.i("Value of i",str);

                JSONObject jsonnode = jsonnodes.getJSONObject(i); 

                JSONObject jsonnodevalue = jsonnode.getJSONObject(API.cheerfoolz_activities.NODE);

                strValue1 = jsonnodevalue.getString(API.cheerfoolz_activities.TITLE);

                Log.i("JSONArray", strValue1);
                //parsedString += " 

 Value of stored parse :  => " + strValue1;
                parsedString = parsedString.trim(); //this will remove the blank white space

                items.add(strValue1);

                parsedString += " 
 Value added in list  => " + items;

                Log.i("Value of items : ", parsedString);



            }


            //List<String> list = Arrays.asList((String[])jsonnodes.toString());
            //String[] values= new String[]{items.toString()};
            //myListView.setListAdapter(

            /* list=(ListView)findViewById(R.id.activity_listView);
               // adapter=new LazyAdapter((Activity) getApplicationContext(), mImages,mTitle);
                list.setAdapter(adapter);*/

            ListView myListView = (ListView)findViewById(R.id.activity_listView);
            myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items));

    //      ArrayAdapter<String> adapter= new ArrayAdapter<String>(Activites_Activity.this, android.R.layout.simple_list_item_1,items);
    //      myListView.setAdapter(adapter);
            //Log.i("contact", items1 );

        }
        catch (JSONException e) {

            e.printStackTrace();
            txtactivity.setText(e.getMessage());

        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

    @Override
    public void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        txtactivity.setText(parsedString);
        pgb.setVisibility(View.GONE);
        //img.setImageResource(parsedString);
    }
}

}

LazyAdapter.java

public class LazyAdapter extends BaseAdapter{

private Activity context;
private String[] title;
private String[] images;
private LayoutInflater inflater;


public LazyAdapter(Activity context,String[] img ,String[] title) {  
    super();  

    this.context = context;  
    this.title = title;  
    this.images = img; 

    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
}  

@Override  
public int getCount() {  
    // TODO Auto-generated method stub  
    return title.length;  
}  

@Override  
public Object getItem(int position) {  
    // TODO Auto-generated method stub  
    return null;  
}  

@Override  
public long getItemId(int position) {  
    // TODO Auto-generated method stub  
    return 0;  
}  

public static class ViewHolder  
{  
    ImageView imgViewLogo;  
    TextView txtViewTitle;  

}  

@Override  
public View getView(int position, View convertView, ViewGroup parent) {  
    // TODO Auto-generated method stub  

    ViewHolder holder;  
    if(convertView==null)  
    {  
        holder = new ViewHolder();  
        convertView = inflater.inflate(R.layout.activity_listitem, null);  

        holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.activity_list_logo);  
        holder.txtViewTitle = (TextView) convertView.findViewById(R.id.activity_list_title);  

        convertView.setTag(holder);  
    }  
    else  
        holder=(ViewHolder)convertView.getTag();  

 //  holder.imgViewLogo.setImageResource(images[position]);  
    holder.txtViewTitle.setText(title[position]);  


    return convertView;  
}   

}

makeWebCall.class

public static String makeWebCall(String url) {

    DefaultHttpClient client = new DefaultHttpClient();

    HttpGet httpRequest = new HttpGet(url);

    try {

        HttpResponse httpResponse = client.execute(httpRequest);

         final int statusCode = httpResponse.getStatusLine().getStatusCode();

         if (statusCode != HttpStatus.SC_OK) {
          /*  Log.i(getClass().getSimpleName(),
                "Error => " + statusCode + " => for URL " + url);*/
            return null;
         }

         HttpEntity entity = httpResponse.getEntity();
            InputStream is = entity.getContent();
            return iStream_to_String(is);
    }
    catch (IOException e) {
        httpRequest.abort();
      // Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
    }

    return null;

 }


public static String iStream_to_String(InputStream is1)
{
     BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
     String line;
     StringBuilder sb =  new StringBuilder();
     try {
        while ((line = rd.readLine()) != null) {
                sb.append(line);
         }
         rd.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     String contentOfMyInputStream = sb.toString();
     return contentOfMyInputStream;
}
最佳回答

假设您的名单上的改动是正确的,那么这部法律就会改变:

ListView myListView = (ListView)findViewById(R.id.activity_listView);
            myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items));

缩略语 <代码>PostExecute功能。 页: 1 浏览,从do InBackground上看,你必须履行保证在活动现场运行的反馈职能之一。

问题回答

暂无回答




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签