0

我的应用程序有问题,当我运行“showContest”活动时,我的应用程序因该错误而崩溃:

03-27 11:18:49.038: E/AndroidRuntime(5279): FATAL EXCEPTION: main
03-27 11:18:49.038: E/AndroidRuntime(5279): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ru.artemzin.android.tutorials.listfragmentexample/time2win.android.ShowContest}: java.lang.NullPointerException
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.os.Looper.loop(Looper.java:137)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.app.ActivityThread.main(ActivityThread.java:5039)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at java.lang.reflect.Method.invokeNative(Native Method)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at java.lang.reflect.Method.invoke(Method.java:511)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at dalvik.system.NativeStart.main(Native Method)
03-27 11:18:49.038: E/AndroidRuntime(5279): Caused by: java.lang.NullPointerException
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:161)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at time2win.android.User.getUserId(User.java:10)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at time2win.android.ShowContest.<init>(ShowContest.java:53)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at java.lang.Class.newInstanceImpl(Native Method)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at java.lang.Class.newInstance(Class.java:1319)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-27 11:18:49.038: E/AndroidRuntime(5279):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-27 11:18:49.038: E/AndroidRuntime(5279):     ... 11 more

表演赛:

package myapp.android;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import ru.artemzin.android.tutorials.listfragmentexample.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ShowContest extends Activity {
    public static String URL = null;
    public static String title = null;
    public static String subtitle = null;
    public static String description = null;
    public static String won = null;
    public static String color = null;
    public static String toDisplay = null;
    public static String arrayPost = null;
    public static int pos;
    public static int nextPosInt;
    public static int backPosInt;
    public static int dataSize;
    public static ArrayList<String> data = null;
    public String idContest = (String) getIntent().getSerializableExtra("id");
    public String pass = User.getUserPass(this);
    public String id = User.getUserId(this);
    ImageView imageView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("Create");




        String etat = null;
        String content = null;
        if (getIntent().getSerializableExtra("participate_sending") != null)
        {
            Document docStat = null;
            System.out.println("In da IF");
            String xmlStat = new XMLfunctionsBack().doInBackground("urltoxml);
            System.out.println("XML request done");
            docStat = XMLfunctions.XMLfromString(xmlStat);
            System.out.println("parsing done");
            NodeList nodesParticipate = docStat.getElementsByTagName("respond");    
            for (int i = 0; i < nodesParticipate.getLength(); i++) {                                        
                Element e = (Element)nodesParticipate.item(i);
                etat = XMLfunctions.getValue(e, "name");
                content = XMLfunctions.getValue(e, "content");
            }
            if (etat == "ERREUR")
            {
                 Toast.makeText(this, content, Toast.LENGTH_LONG).show();
            }
            if (etat == "OK")
            {
                Toast.makeText(this, content, Toast.LENGTH_LONG).show();
            }
            else
                Toast.makeText(this, "Strange ERROR", Toast.LENGTH_LONG).show();            
        }
        System.out.println("After da IF");
        /*********************Fetch Contest content*******************/
        //Needed for arrow navigation
        final Serializable posSerialize = getIntent().getSerializableExtra("pos");
        pos = Integer.parseInt((String) getIntent().getSerializableExtra("pos"));
        data = getIntent().getStringArrayListExtra("data");
        nextPosInt = pos +1;
        backPosInt = pos -1;
        dataSize = data.size() -1;
        String xml = new XMLfunctionsBack().doInBackground(urltoyml);
        Document doc = XMLfunctions.XMLfromString(xml);

        NodeList nodes = doc.getElementsByTagName("contest");   
        for (int i = 0; i < nodes.getLength(); i++) {                                       
            Element e = (Element)nodes.item(i);
            URL = "urltoimage);
            title = XMLfunctions.getValue(e, "name");
            subtitle = XMLfunctions.getValue(e, "subtitle");
            description = XMLfunctions.getValue(e, "description");
            won = XMLfunctions.getValue(e, "description");
            color = "#" + XMLfunctions.getValue(e, "color");
            toDisplay  = XMLfunctions.getValue(e, "text_to_display");
        }





        setContentView(R.layout.show_contest);
        imageView = (ImageView) findViewById(R.id.imageView);
        TextView titleText = (TextView) findViewById(R.id.textView1);
        titleText.setText(title);
        titleText.setTextColor(Color.parseColor(color));

        TextView subtitleText = (TextView) findViewById(R.id.textView2);
        subtitleText.setText(subtitle);

        TextView descriptionText = (TextView) findViewById(R.id.textView3);
        descriptionText.setText(description);

        TextView toDisplayText = (TextView) findViewById(R.id.todisplay);
        toDisplayText.setText(toDisplay);
        toDisplayText.setTextColor(Color.parseColor(color));
        // Create an object for subclass of AsyncTask
        GetXMLTask task = new GetXMLTask();
        // Execute the task
        task.execute(new String[] { URL });

        Button button = (Button) findViewById(R.id.participer);

        button.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            Intent intent = new Intent(getBaseContext(), Participate.class);
            intent.putExtra("id",idContest);
            intent.putExtra("pos",posSerialize);
            intent.putStringArrayListExtra( "data", data);
            startActivity(intent);

          }
        });

    }
    /************************Top Menu nav*****************************/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.activity_main, menu);
      return true;
    } 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case R.id.action_forward:
        if (dataSize > pos)
        {

            String nextPos = String.valueOf(nextPosInt);
            String next = data.get(nextPosInt);
            Intent intent = new Intent(this, ShowContest.class);
            intent.putExtra("id", next);
            intent.putExtra("pos",nextPos);
            intent.putStringArrayListExtra( "data", data);
            startActivity(intent); 
        }
        else
        {
            Toast.makeText(this, "Vous êtes déjà au dernier concour", Toast.LENGTH_LONG)
            .show();
        }
        break;
      case R.id.action_back:
        if (0 < pos)
        {

            String backPos = String.valueOf(backPosInt);
            String back = data.get(backPosInt);
            Intent intent = new Intent(this, ShowContest.class);
            intent.putExtra("id", back);
            intent.putExtra("pos",backPos);
            intent.putStringArrayListExtra( "data", data);
            startActivity(intent); 
        }
        else
        {
            Toast.makeText(this, "Vous êtes déjà au premier concour", Toast.LENGTH_LONG)
              .show();
        }
        break;
      case R.id.boutique:
            Intent intentBoutique = new Intent(this, MainActivity.class);
            intentBoutique.putExtra("type", "1");
            startActivity(intentBoutique); 
      case R.id.restaurant:
            Intent intentRestaurant = new Intent(this, MainActivity.class);
            intentRestaurant.putExtra("type", "2");
            startActivity(intentRestaurant);
      case R.id.nightlife:
            Intent intentNightlife = new Intent(this, MainActivity.class);
            intentNightlife.putExtra("type", "3");
            startActivity(intentNightlife);
      case R.id.loisir:
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("type", "4");
            startActivity(intent);
      case R.id.evenement:
            Intent intentEvenement = new Intent(this, MainActivity.class);
            intentEvenement.putExtra("type", "5");
            startActivity(intentEvenement);

      default:
        break;
      }

      return true;
    } 


    /************************Image part******************************/
    private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... urls) {
            Bitmap map = null;
            for (String url : urls) {
                map = downloadImage(url);
            }
            return map;
        }

        // Sets the Bitmap returned by doInBackground
        @Override
        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
        }

        // Creates Bitmap from InputStream and returns it
        private Bitmap downloadImage(String url) {
            Bitmap bitmap = null;
            InputStream stream = null;
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inSampleSize = 1;

            try {
                stream = getHttpConnection(url);
                bitmap = BitmapFactory.
                        decodeStream(stream, null, bmOptions);
                stream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return bitmap;
        }

        // Makes HttpURLConnection and returns InputStream
        private InputStream getHttpConnection(String urlString)
                throws IOException {
            InputStream stream = null;
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();

            try {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return stream;
        }
    }
}

用户等级:

public class User {
    public final static String PREFS_NAME = "UserData";
    public static String getUserId(Context context)
    {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        String id = settings.getString("id", "");
        return id;
    }

    public static String getUserPass(Context context)
    {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        String pass = settings.getString("pass", "");
        return pass;
    }

}

如果我在没有 UI 部分的情况下评论我的所有代码所有工作,但如果我不评论 idContest 或 / 和 id/pass 应用程序崩溃......

所有这些变量都不为空,我不知道为什么我的应用程序崩溃了......

我已经清理了我的项目。

谢谢

4

2 回答 2

1

您太早地使用共享首选项初始化变量而无法获得有效的上下文。

所以不是public String id = User.getUserId(this);在你的类变量中,而是在onCreate方法内初始化变量id = User.getUserId(getApplicationContext());

也初始化里面的其他变量onCreate

于 2013-03-27T11:36:40.067 回答
0

你在崩溃堆栈跟踪之前找到一条日志消息AndroidRuntime D Shutting down VM,对吧?

当你再次运行你的应用程序时,你会得到这个堆栈跟踪,而它已经安装并在设备上运行,对吧?

问题解决了:忽略它!

原因:当你重新安装它时,你的应用程序可能仍然会做一些事情。因此,android 会尝试从 APK 中加载一些已经/已经被新的 APK 替换的内容。

我可以很容易地重现这一点:当我的应用程序在我的登录屏幕上时(没有完成背景工作),重新安装不会触发崩溃,但它会在我登录并进行一些下载/同步等操作后立即出现。

没有什么可担心的。每个开发人员在再次运行项目时应该已经看到“应用程序已崩溃”对话框。它只会发生在你身边,永远不会发生在用户端。

我的猜测:JIT 是负责任的,你不能对它做任何事情(这没关系)。

于 2013-03-27T11:03:33.803 回答