android.content.res.Resources $ NotFoundException:字符串资源ID#0x2

时间:2015-09-03 21:46:27

标签: java android

  

这是从json对象

获取数据的ma java代码
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class OutboxActivity extends Activity {
    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> outboxList;
    /*************************************************************************************************/
    List<String> too = new ArrayList<String>();
    List<String> sub = new ArrayList<String>();
    List<String> datel = new ArrayList<String>();
/**********************************************************************/

    // products JSONArray
    JSONArray outbox = null;

    // Outbox JSON url
    private static final String OUTBOX_URL = "http://www.bitfutura.in/outbox123.json";

    // ALL JSON node names
    private static final String TAG_MESSAGES = "messages";
    private static final String TAG_ID = "id";
    private static final String TAG_TO = "to";
    private static final String TAG_SUBJECT = "subject";
    private static final String TAG_DATE = "date";
     SQLiteDatabase dbs;
    ListView list;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbs=openOrCreateDatabase("mycar.db",MODE_PRIVATE,null);
        dbs.execSQL("create table if not exists Outbox(id varchar,top varchar,subject varchar,messsage" +
                " varchar,date varchar)");


        // Hashmap for ListView
        outboxList = new ArrayList<HashMap<String, String>>();

        // Loading OUTBOX in Background Thread
        new LoadOutbox().execute();
    }

    /**
     * Background Async Task to Load all OUTBOX messages by making HTTP Request
     * */
    class LoadOutbox extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(OutboxActivity.this);
            pDialog.setMessage("Loading Outbox ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Outbox JSON
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(OUTBOX_URL, "GET",
                    params);

            // Check your log cat for JSON reponse
            Log.d("Outbox JSON: ", json.toString());

            try {
                outbox = json.getJSONArray(TAG_MESSAGES);
                // looping through All messages
                dbs.execSQL("DELETE FROM Outbox");
                for (int i = 0; i < outbox.length(); i++) {
                    JSONObject c = outbox.getJSONObject(i);
                    /***************************************************/





                    /************************************************/

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String to = c.getString(TAG_TO);
                    String subject = c.getString(TAG_SUBJECT);
                    String date = c.getString(TAG_DATE);
                    /****************************************************************/
                    too.add(to);
                    sub.add(subject);
                    datel.add(date);
                    /*********************************************************************/


                    String shu="'"+id+"','"+to+"','"+subject+"','"+date+"','"+date+"'";
                    dbs.execSQL("insert into Outbox values("+shu+")");


                    // subject taking only first 23 chars
                    // to fit into screen

                    if(subject.length() > 23){
                        subject = subject.substring(0, 22) + "..";
                    }

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_TO, to);
                    map.put(TAG_SUBJECT, subject);
                    map.put(TAG_DATE, date);

                    // adding HashList to ArrayList

                    outboxList.add(map);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    String[] toa = new String[too.size()];
                    toa = too.toArray(toa);
                    String[] suba = new String[sub.size()];
                    suba = sub.toArray(suba);
                    String[] datea = new String[datel.size()];
                    datea = datel.toArray(datea);
                    /*
                    ListAdapter adapter = new SimpleAdapter(
                            OutboxActivity.this, outboxList,
                            R.layout.outbox_list_item, new String[] { TAG_SUBJECT, TAG_TO, TAG_DATE },
                            new int[] { R.id.subject, R.id.to, R.id.date });
                    // updating listview
                    setListAdapter(adapter);
                    */
                    EventAdapter adapter=new EventAdapter(OutboxActivity.this,toa,suba,datea);
                    list=(ListView)findViewById(R.id.list);
                    list.setAdapter(adapter);
                        try {
                            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                @Override
                                public void onItemClick(AdapterView<?> parent, View view,
                                                        int position, long id) {
                                    // TODO Auto-generated method stub
                                    int Slecteditem = position;
                                    Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();

                                }
                            });
                        }catch(Exception ae)
                        {
                            Toast.makeText(getApplicationContext(),ae.getMessage(), Toast.LENGTH_LONG).show();
                        }
                }
            });

        }

    }
}
  

这是我的事件适配器类

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class EventAdapter extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] itemname;
    private final String[] itemname2;
    private final String[] itemname3;

    public EventAdapter(Activity context, String[] itemname,String[] itemname3,String[] itemname2) {
        super(context, R.layout.myevent, itemname);
        // TODO Auto-generated constructor stub

        this.context=context;
        this.itemname=itemname;
        this.itemname3=itemname3;
        this.itemname2=itemname2;

    }

    public View getView(int position,View view,ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.myevent, null, true);

        TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
        TextView extratxt1 = (TextView) rowView.findViewById(R.id.textView1);
        TextView extratxt2 = (TextView) rowView.findViewById(R.id.textView2);

        txtTitle.setText(itemname[position]);
        extratxt1.setText(itemname2[position]);
        extratxt2.setText(itemname3[position]);
        return rowView;

    };
}
  

这是我的用于列表视图的Activitymain xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</RelativeLayout>
  

列表视图成功获取更新但是当我单击列表视图中显示吐司的选项时,我单击它的位置显示错误

    android.content.res.Resources$NotFoundException: String resource ID #0x2
            at android.content.res.Resources.getText(Resources.java:274)
            at android.widget.Toast.makeText(Toast.java:277)
            at com.dk.sample.folder.residemenu.OutboxActivity$LoadOutbox$1$1.onItemClick(OutboxActivity.java:200)
            at android.widget.AdapterView.performItemClick(AdapterView.java:300)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
            at android.widget.AbsListView.onTouchUp(AbsListView.java:3845)
            at android.widget.AbsListView.onTouchEvent(AbsListView.java:3617)
            at android.view.View.dispatchTouchEvent(View.java:8388)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2424)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2158)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2314)
            at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1692)
            at android.app.Activity.dispatchTouchEvent(Activity.java:2739)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2275)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)

1 个答案:

答案 0 :(得分:3)

int Slecteditem = position;
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();

您正在使用message参数的项目位置。 Toast不知道你的适配器并且认为你给它一个字符串资源ID,但是找不到具有该ID的字符串(在这种情况下是2)。您需要使用实际的字符串资源ID或实际的String。

由于您的适配器扩展了ArrayAdapter,您可以使用adapter.getItem(position)代替(我怀疑您打算这样做)。