Parcelable and JSON in android

拥有回忆 提交于 2019-12-12 06:45:47

问题


I am working on a project where i have a URL in JSONObjects and i have to show those items in a listview with the course names being the items. When the user clicks a course name in the list, a new activity must open with the grades and the coefficient available there in a similar listview. (those informations are available at http://benitobertoli.com/grades.html ) I wrote a code but i got stuck when it arrived to send data from the first activity to the other via parcelable.. can anyone PLEASE help me and show me how to do it ?

This is my code:

public class MainActivityJSON extends ListActivity
{

protected String[] mBlogPostTitles;
public static final String TAG = MainActivityJSON.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;

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

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
    mProgressBar.setVisibility(View.VISIBLE);

    if(isNetworkAvailable())
    {
        GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
        getBlogPostsTask.execute();
    }
    else
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("ERROR !!");
            builder.setMessage("Sorry there was an error getting data from the Internet.\nNetwork Unavailable!");
            builder.setPositiveButton(android.R.string.ok, null);
            AlertDialog dialog = builder.create();
            dialog.show();
            Toast.makeText(this, "Network Unavailable!", Toast.LENGTH_LONG).show();
        }
}

private boolean isNetworkAvailable()
{
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if(networkInfo != null  && networkInfo.isConnected())
    {
        isAvailable = true;
        return isAvailable;
    }
    else
        return isAvailable;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_activity_json, menu);
    return true;
}

private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject>
{

    @Override
    protected JSONObject doInBackground(Object... arg0)
    {
        int responseCode = -1;
        JSONObject jsonResponse = null;

        try
        {
            URL blogFeedUrl = new URL("http://benitobertoli.com/grades.html");
            HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
            connection.connect();

            responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK)
            {
                InputStream inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream);
                int contentLength = connection.getContentLength();
                char[] charArray = new char[contentLength];
                reader.read(charArray);
                String responseData = new String(charArray);

                jsonResponse = new JSONObject(responseData);

            }
            else
            {
                Log.i(TAG, "Unsuccessfull Http Response Code: " + responseCode);
            }

        }catch (MalformedURLException e) { Log.e(TAG, "Exception caught ", e);
        }catch (IOException e) { Log.e(TAG, "Exception caught ", e);
        }catch (Exception e) { Log.e(TAG, "Exception caught ", e);
        }
        return jsonResponse;
    }

    @Override
    protected void onPostExecute(JSONObject result)
    {
        mBlogData = result;
        updateList();
    }

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void updateList()
{
    mProgressBar.setVisibility(View.INVISIBLE);
    if(mBlogData == null)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("ERROR !!");
        builder.setMessage("Sorry there was an error getting data from the Internet");
        builder.setPositiveButton(android.R.string.ok, null);
        AlertDialog dialog = builder.create();
        dialog.show();

        TextView emptyTextView = (TextView) getListView().getEmptyView();
        emptyTextView.setText(getString(R.string.no_items));

    }
    else {
        try {
            JSONArray jsonPosts = mBlogData.getJSONArray("data");
            mBlogPostTitles = new String[jsonPosts.length()];
            //ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
            for(int i =0 ; i < jsonPosts.length() ; i++)
            {
                JSONObject post = jsonPosts.getJSONObject(i);
                String course = post.getString("course");
                course = Html.fromHtml(course).toString();
                //String coet = post.getString("coet");
                //coet = Html.fromHtml(coet).toString();

                //HashMap<String, String> blogPost = new HashMap<String, String>();
                //blogPost.put("course", course);
                //blogPost.put("coet", "coefficient: "+coet);

                //blogPosts.add(blogPost);

                mBlogPostTitles[i] = course;

            }

            //String[] keys = { "course","coet" };
            //int[] ids = { android.R.id.text1 , android.R.id.text2 };
            //SimpleAdapter adapter = new SimpleAdapter(this, blogPosts, android.R.layout.simple_list_item_2, keys, ids);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 
                    mBlogPostTitles);
            setListAdapter(adapter);
        } catch (JSONException e) {
            Log.e(TAG, "Exception caught", e);
        }
    }

}

 public void PacelableMethod()
 { 
       Send mSend = new Send();  
       Intent mIntent = new Intent(this, DetailsJSON.class); 
       Bundle mBundle = new Bundle(); 
       mBundle.putParcelable(key, mSend); 
       mIntent.putExtras(mBundle); 

       startActivity(mIntent); 
    }  

public class Send implements Parcelable
{ 
    private String trim1; 
    private String trim2; 
    private String trim3;
    private String finalgrade;

    public String getTrim1() { 
        return trim1; 
    } 
    public void setTrim1(String Trim1) { 
        this.trim1 = Trim1; 
    } 
    public String getTrim2() { 
        return trim2; 
    } 
    public void setTrim2(String Trim2) { 
        this.trim2 = Trim2; 
    } 
    public String getPublishTime() { 
        return trim3; 
    } 
    public void setPublishTime(String Trim3) { 
        this.trim3 = Trim3; 
    }
    public String getFinalgrade() {
        return finalgrade;
    }
    public void setFinalgrade(String finalgrade) {
        this.finalgrade = finalgrade;
    } 

    public final Parcelable.Creator<Send> CREATOR = new Creator<Send>()
    { 
        public Send createFromParcel(Parcel source)
        { 
            Send mBook = new Send(); 
            mBook.trim1 = source.readString(); 
            mBook.trim2 = source.readString(); 
            mBook.trim3 = source.readString(); 
            return mBook; 
        } 
        public Send[] newArray(int size)
        { 
            return new Send[size]; 
        } 
    };

    public int describeContents()
    { 
        return 0; 
    } 
    public void writeToParcel(Parcel parcel, int flags)
    { 
        parcel.writeString(trim1); 
        parcel.writeString(trim2); 
        parcel.writeString(trim3); 
    }
}  
}

回答1:


Change your class "Send" to

public class Send implements Parcelable { 
private String trim1; 
private String trim2; 
private String trim3;
private String finalgrade;

public String getTrim1() { 
    return trim1; 
} 
public void setTrim1(String Trim1) { 
    this.trim1 = Trim1; 
} 
public String getTrim2() { 
    return trim2; 
} 
public void setTrim2(String Trim2) { 
    this.trim2 = Trim2; 
} 
public String getPublishTime() { 
    return trim3; 
} 
public void setPublishTime(String Trim3) { 
    this.trim3 = Trim3; 
}
public String getFinalgrade() {
    return finalgrade;
}
public void setFinalgrade(String finalgrade) {
    this.finalgrade = finalgrade;
} 

protected Send(Parcel in) {
    trim1 = in.readString();
    trim2 = in.readString();
    trim3 = in.readString();
    finalgrade = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(trim1);
    dest.writeString(trim2);
    dest.writeString(trim3);
    dest.writeString(finalgrade);
}

@SuppressWarnings("unused")
public static final Parcelable.Creator<Send> CREATOR = new Parcelable.Creator<Send>() {
    @Override
    public Send createFromParcel(Parcel in) {
        return new Send(in);
    }

    @Override
    public Send[] newArray(int size) {
        return new Send[size];
    }
};

}

and try.



来源:https://stackoverflow.com/questions/24508194/parcelable-and-json-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!