Android Json Parsing App

时间:2015-02-14 17:11:27

标签: android json parsing

应用程序在启动几秒钟后崩溃

//我的主要课程//

 package jsontutorial.wingnity.com.quotefuel;

    import android.app.Activity;
    import android.graphics.Typeface;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.TextView;


    public class Main extends Activity {

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

            //Font Path
            String fontpath = "Oswald-Light.ttf";
            TextView ourText = (TextView)findViewById(R.id.textView);
            Typeface tf = Typeface.createFromAsset(getAssets(),fontpath);
            ourText.setTypeface(tf);
            MyClass myclass = new MyClass();
            myclass.execute("http://api.icndb.com/jokes/random/");



        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @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();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }



    }

//My AsyncClass//

package jsontutorial.wingnity.com.quotefuel;


import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.IOException;

/**
 * Created by ABHIJITH T on 14-02-2015.
 */
public  class MyClass extends AsyncTask<String,Void,Boolean> {
String h;
    @Override
    protected Boolean doInBackground(String... params) {

        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(params[0]);
            HttpResponse response = client.execute(post);

            int status = response.getStatusLine().getStatusCode();
            if (status==200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);


                JSONObject jObj = new JSONObject(data);
                String receivedJoke = jObj.getString("joke");
                this.h=receivedJoke;
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        if(result==false){
            Main m = new Main();
            Toast.makeText(m, "Can't connect to internet", Toast.LENGTH_SHORT).show();
        }else {
            TextView t=null ;
            t.findViewById(R.id.textView);
            t.setText(h);
        }
    }
}

// ADB LOG //

02-14 22:24:04.300    1989-1989/jsontutorial.wingnity.com.quotefuel E/libprocessgroup﹕ failed to make and chown /acct/uid_10054: Read-only file system
02-14 22:28:11.767    2045-2045/jsontutorial.wingnity.com.quotefuel E/libprocessgroup﹕ failed to make and chown /acct/uid_10054: Read-only file system
02-14 22:28:17.353    2045-2045/jsontutorial.wingnity.com.quotefuel E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: jsontutorial.wingnity.com.quotefuel, PID: 2045
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
            at android.content.ContextWrapper.getResources(ContextWrapper.java:85)
            at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
            at android.widget.Toast.<init>(Toast.java:101)
            at android.widget.Toast.makeText(Toast.java:250)
            at jsontutorial.wingnity.com.quotefuel.MyClass.onPostExecute(MyClass.java:59)
            at jsontutorial.wingnity.com.quotefuel.MyClass.onPostExecute(MyClass.java:22)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

1 个答案:

答案 0 :(得分:0)

在onPostExecute的else语句中替换

 TextView t=null ;
        t.findViewById(R.id.textView);
        t.setText(h);

通过

  TextView t=(getApplicationContext())findViewById(R.id.textView);
 t.setText(h);

 TextView t=(getActivity())findViewById(R.id.textView);
 t.setText(h);

此外,需要在if语句中修改toast。 用getActivity()或getApplicationContext()

替换toast的上下文