0

Help me please with error FATAL EXCEPTION main

I have this error when new activity starts.

my code:

package com.novator.inweld;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

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.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;

public class News extends Activity
{
    @SuppressLint({ "NewApi", "ResourceAsColor" }) @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news);

        StrictMode.enableDefaults();

        String result = "";
        InputStream isr = null;

        try
        {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://test.ivanov-vladimir.com/get_news.php");
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "HTTP connect error " + e.toString());
        }

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "utf-8"), 8);
            StringBuilder builder = new StringBuilder();
            String line = null;

            while((line = reader.readLine()) != null)
            {
                builder.append(line + "\n");
                Log.v("line", line);
            }

            isr.close();
            result = builder.toString();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Data converting error " + e.toString());
        }

        try
        {
            JSONArray jarray = new JSONArray(result);
            String s;
            TextView title;
            int textId;

            for(int i = 0; i < jarray.length(); i++)
            {
                textId = i + 1;

                JSONObject json = jarray.getJSONObject(i);
                s = json.getString("title") + "  -  " + json.getString("date") + "\n\n" + json.getString("content");

                title = new TextView(this);
                title.setTextColor(getResources().getColor(R.color.colorWihte));
                title.setShadowLayer(2, 0, 0,getResources().getColor(R.color.colorBlack));
                title.setBackground(getResources().getDrawable(R.drawable.round_block));
                title.setId(textId);
                title.setText(s);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

                if(i == 0)
                {

                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    title.setLayoutParams(layoutParams);
                }
                else
                {
                    layoutParams.addRule(RelativeLayout.BELOW, textId - 1);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    layoutParams.setMargins(0, 20, 0, 0);
                    title.setLayoutParams(layoutParams);
                }

                ((ViewGroup) findViewById(R.id.newslayout)).addView(title);
            }
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Data parsing error " + e.toString());
        }
    }
}

logs:

12-30 10:18:21.673: D/dalvikvm(324): VFY: replacing opcode 0x71 at 0x000d
12-30 10:18:21.683: D/dalvikvm(324): VFY: dead code 0x0010-01cd in Lcom/novator/inweld/News;.onCreate (Landroid/os/Bundle;)V
12-30 10:18:21.873: D/dalvikvm(324): GC_EXTERNAL_ALLOC freed 2959 objects / 152376 bytes in 148ms
12-30 10:18:22.583: D/AndroidRuntime(324): Shutting down VM
12-30 10:18:22.583: W/dalvikvm(324): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
12-30 10:18:22.603: E/AndroidRuntime(324): FATAL EXCEPTION: main
12-30 10:18:22.603: E/AndroidRuntime(324): java.lang.NoClassDefFoundError: android.os.StrictMode
12-30 10:18:22.603: E/AndroidRuntime(324):  at com.novator.inweld.News.onCreate(News.java:32)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.os.Looper.loop(Looper.java:123)
12-30 10:18:22.603: E/AndroidRuntime(324):  at android.app.ActivityThread.main(ActivityThread.java:4627)
12-30 10:18:22.603: E/AndroidRuntime(324):  at java.lang.reflect.Method.invokeNative(Native Method)
12-30 10:18:22.603: E/AndroidRuntime(324):  at java.lang.reflect.Method.invoke(Method.java:521)
12-30 10:18:22.603: E/AndroidRuntime(324):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-30 10:18:22.603: E/AndroidRuntime(324):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-30 10:18:22.603: E/AndroidRuntime(324):  at dalvik.system.NativeStart.main(Native Method)
Chintan Khetiya
  • 15,962
  • 9
  • 47
  • 85
Vladimir
  • 229
  • 2
  • 16

2 Answers2

1

You should use a thread or Asynctask for network related operation

http://developer.android.com/reference/android/os/AsyncTask.html

Read the topic The 4 Steps in the above link.

http://developer.android.com/reference/android/os/StrictMode.html

StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them.

To invoke Asynctask

  new TheTask().execute();

The

 class TheTask extends Asynctask<Void,String,String>
  {
      @Override
      public String doInbackground(Void... params)
      {
        String response=null;  
        try
        {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://test.ivanov-vladimir.com/get_news.php");
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        response = EntityUtils.toString(entity); 
        }
        catch(Exception e)
        {
        Log.e("log_tag", "HTTP connect error " + e.toString());
        }
       return response;
      } 
      @Override 
      protected void onPostExecute(String result)
      {
          super.onPostExecute(result);
          Log.i("Result is ....",result); 
      }  
  } 

Note : you cannot update ui from a background thread. Use onPostExecute to update ui

Also instead of creating textview's in a for loop you can use use a listview.

You can also use a custom adapter inflate a layout with textview and style the textview also.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • I delete code part: title.setTextColor(getResources().getColor(R.color.colorWihte)); title.setShadowLayer(2, 0, 0,getResources().getColor(R.color.colorBlack)); and it works now! error occurred because the system did not have time to appoint background and color between tasks execute? – Vladimir Dec 30 '13 at 07:20
  • @Vladimir what code part. in onCreate invoke asynctask and make your asynctask an inner class of activity class. StrictMode is not necessary – Raghunandan Dec 30 '13 at 07:23
  • @Vladimir still you should use asynctask or thread for n/w related operation. The error is `NoClassDefFoundError` which has nothing to do with asynctask. But you should consider using one. and also consider using listview. you don't want to create 100 textviews depending on the response. you can use listview which recycles views. So choose the better option. since you asked for the example i posted one – Raghunandan Dec 30 '13 at 07:30
  • Thanx, i created async http request! – Vladimir Dec 30 '13 at 09:23
  • @Vladimir nice. that is way to go – Raghunandan Dec 30 '13 at 15:18
0

Issue is about your class path. NoClassDefFoundError

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Fore More Details

How to solve this ?

Check This ,This , This

Along with that you are trying to call your WebAPI in your UI thread which id not good at all.

Try you use AsyncTask so that will load your data in background without effect on your UI.Check Sample Example.

Community
  • 1
  • 1
Chintan Khetiya
  • 15,962
  • 9
  • 47
  • 85