AsyncTask #1 :An error occured while executing doInBackground() - java

I am developing app with Jsoup. The problem is it is not working when I am calling it from other class with the help of Getters. But it is running when I call it within Single Activity. I am not able to find why exactly it is not working, as it should.
Here are the logCat files with all the activities.
LogCat
11-14 20:16:52.063: E/AndroidRuntime(1871): FATAL EXCEPTION: AsyncTask #1
11-14 20:16:52.063: E/AndroidRuntime(1871): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.lang.Thread.run(Thread.java:856)
11-14 20:16:52.063: E/AndroidRuntime(1871): Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.Jsoup.connect(Jsoup.java:73)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-14 20:16:52.063: E/AndroidRuntime(1871): ... 4 more
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(getApplicationContext(), LineGraph.class);
startActivity(i);
}
}
LineGraph
public class LineGraph extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsoupAct mJsoupAct = new jsoupAct();
String parseStrings;
parseStrings = mJsoupAct.getOutput();
Log.d("xstring", parseStrings + "");
}
}
jsoupAct
public class jsoupAct extends Activity {
String output = "00";
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
url = "www.google.com";
}
public void mExecute() {
new Parsee().execute();
}
public class Parsee extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(url).get();
String body = doc.body().text();
output = body.toString();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(output);
}
}
public String getOutput() {
mExecute();
return output;
}
public void setOutput(String output) {
this.output = output;
}
}

You are specifying the URL in a string local to the jsoupAct activity. The string will be null if you try to access from other Activities. To solve it move the string inside the AsyncTask class and it will work
Or add empty constructor to the jsonAct activity and assign the value of url in it. onCreate() is called only when to start an activity using the startActivity()

You have already answered your own question:
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more

Related

App crash if I try to open a fragment in an activity

every time I try to open my fragment in my MainActivity.class my app crashs.
MainActivity.class
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(getApplicationContext(), AddServerFragment.class);
startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
...
public class AddServerFragment extends Fragment {
public AddServerFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.add_ip, container, false);
Button btn_back, btn_add;
final EditText server_ip, server_name;
server_ip = (EditText) findViewById(R.id.edit_server_address);
server_name = (EditText) findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String new_server_ip = null, new_server_name = null;
ArrayList<String> server_name_list = new ArrayList<String>();
ArrayList<String> server_ip_list = new ArrayList<String>();
new_server_ip = server_ip.getText().toString();
server_ip_list.add(new_server_ip);
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
return rootView;
}
}
My errorlog only say, I have to add the Fragment in my Manifest.xml as activity. But I know, I don't have to add it there.
Errorlog
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: FATAL EXCEPTION: main
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: Process: de.kwietzorek.fulcrumwebview, PID: 18345
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: android.content.ActivityNotFoundException: Unable to find explicit activity class {de.kwietzorek.fulcrumwebview/de.kwietzorek.fulcrumwebview.MainActivity$AddServerFragment}; have you declared this activity in your AndroidManifest.xml?
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3917)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3877)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4200)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4168)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at de.kwietzorek.fulcrumwebview.MainActivity.onOptionsItemSelected(MainActivity.java:90)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.onMenuItemSelected(Activity.java:2908)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.onMenuItemSelected(AppCompatDelegateImplV7.java:621)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:191)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AdapterView.performItemClick(AdapterView.java:310)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView$PerformClick.run(AbsListView.java:3042)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView$3.run(AbsListView.java:3879)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Edit
My Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Wrong with the above code:
ERROR Intent intent = new Intent(getApplicationContext(), AddServerFragment.class);
startActivity(intent);
Use the correct method for using fragment, you have used method for starting activity.
AddServerFragment is Fragment not activity.
For fragment to add in activity, you have to use the following approach:
In your activity,
XML code part in activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java Code Part in MainActivity.class:
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
// Create an instance of AddServerFragment
AddServerFragment firstFragment = new AddServerFragment();
// if there are any extras
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
You need to add the activity declaration to your manifest file:
<activity android:name=".MainActivity" >
</activity>
You cant use intent when you want open fragment.
You can try FragmentManager.
Example:
public void getFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
if (mFragment == null) {
mFragment = fragment;
fm.beginTransaction()
.add(R.id.fragment_container, mFragment)
.commit();
}
if (mFragment != null) {
mFragment = fragment;
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}

getting Null Pointer Exception to parse Json data using Gson [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I just parse the json data using Gson.but it gives a NullPointerException
this is my json file here JSON File
This is my CustomAdapter which handles the operation and add the data to listview
MyCustomAdapter
package com.vap.gsonexample;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Virat Puar on 14-11-2015.
*/
public class CustomAdapter extends BaseAdapter {
private List<Response.DataEntity> weatheritem;
private Context mcontext;
private LayoutInflater inflater;
public CustomAdapter(Context mcontext, List<Response.DataEntity> weatheritem) {
this.mcontext = mcontext;
this.weatheritem = weatheritem;
}
#Override
public int getCount() {
return weatheritem.size();
}
#Override
public Object getItem(int position) {
return weatheritem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater)mcontext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =inflater.inflate(R.layout.each_item,parent,false);
Response.DataEntity dataEntity = (Response.DataEntity) getItem(position);
ImageView thumbnial = (ImageView) view.findViewById(R.id.thumbnial);
TextView date = (TextView) view.findViewById(R.id.date);
TextView weathercode = (TextView) view.findViewById(R.id.weathercode);
String imageUrl = dataEntity.getWeather().get(position).getWeatherIconUrl().get(position).getValue();
date.setText(dataEntity.getWeather().get(position).getDate());
weathercode.setText(dataEntity.getWeather().get(position).getWeatherCode());
Picasso.with(mcontext).load(imageUrl).into(thumbnial);
return view;
}
}
This is my Main Activity code where error occurs MainActivity
package com.vap.gsonexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.lang.reflect.Type;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity {
Response response;
CustomAdapter customAdapter;
String url ="http://api.worldweatheronline.com/free/v1/weather.ashx?" +
"q=Rajkot&format=json&num_of_days=5&key=xz9js2zhayhj4bcxuf7br2bg";
Gson gson;
AsyncHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.listView);
client = new AsyncHttpClient();
client.get(MainActivity.this,url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String responsestr = new String(responseBody);
Type listtype = new TypeToken<Response>(){}.getType();
Response response = gson.fromJson(responsestr, listtype);
customAdapter = new CustomAdapter(MainActivity.this, (List<Response.DataEntity>) response.getData());
listView.setAdapter(customAdapter);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplication(),"Fail"+statusCode+error,Toast.LENGTH_LONG).show();
}
});
}
}
And Finally this is my log file
E/AndroidRuntime: FATAL EXCEPTION: main
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: java.lang.RuntimeException: java.lang.ClassCastException: com.vap.gsonexample.Response$DataEntity cannot be cast to java.util.List
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: Caused by: java.lang.ClassCastException: com.vap.gsonexample.Response$DataEntity cannot be cast to java.util.List
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.vap.gsonexample.MainActivity$1.onSuccess(MainActivity.java:40)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:351)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4745) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) 
11-14 07:25:32.394 119-173/? E/SocketStream: readFully was waiting for 403440 bytes, got 16192
11-14 07:25:32.394 119-173/? E/SocketStream: readFully was waiting for 387248 bytes, got 16192
11-14 07:25:32.394 119-173/? E/SocketStream: readFully was waiting for 371056 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 354864 bytes, got 15664
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 339200 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 323008 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 306816 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 290624 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 274432 bytes, got 8232
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 266200 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 250008 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 233816 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 217624 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 201432 bytes, got 8232
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 193200 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 177008 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 160816 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 144624 bytes, got 15664
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 128960 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 112768 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 96576 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 80384 bytes, got 15664
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 64720 bytes, got 16192
11-14 07:25:32.410 119-173/? E/SocketStream: readFully was waiting for 48528 bytes, got 16192
11-14 07:25:32.410 119-173/? E/SocketStream: readFully was waiting for 32336 bytes, got 16192
11-14 07:33:23.734 119-173/? E/SocketStream: readFully was waiting for 403440 bytes, got 16192
11-14 07:33:23.734 119-173/? E/SocketStream: readFully was waiting for 387248 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 371056 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 354864 bytes, got 15664
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 339200 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 323008 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 306816 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 290624 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 274432 bytes, got 8232
11-14 07:33:23.742 119-173/? E/SocketStream: readFully was waiting for 266200 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 250008 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 233816 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 217624 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 201432 bytes, got 8232
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 193200 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 177008 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 160816 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 144624 bytes, got 16192
11-14 07:33:23.750 119-173/? E/SocketStream: readFully was waiting for 128432 bytes, got 8232
11-14 07:33:23.750 119-173/? E/SocketStream: readFully was waiting for 120200 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 104008 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 87816 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 71624 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 55432 bytes, got 8232
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 47200 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 31008 bytes, got 16192
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: User-space exception detected!
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: java.lang.NullPointerException
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.vap.gsonexample.MainActivity$1.onSuccess(MainActivity.java:36)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:351)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at android.os.Looper.loop(Looper.java:137)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at java.lang.reflect.Method.invokeNative(Native Method)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at java.lang.reflect.Method.invoke(Method.java:511)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at dalvik.system.NativeStart.main(Native Method)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: FATAL EXCEPTION: main
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: java.lang.RuntimeException: java.lang.NullPointerException
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.vap.gsonexample.MainActivity$1.onSuccess(MainActivity.java:36)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:351)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510) 
Please help someone to find this error.
This is my Response model
package com.vap.gsonexample;
import java.util.List;
/**
* Created by Virat Puar on 14-11-2015.
*/
public class Response {
private DataEntity data;
public void setData(DataEntity data) {
this.data = data;
}
public DataEntity getData() {
return data;
}
public class DataEntity {
private List<RequestEntity> request;
private List<Current_conditionEntity> current_condition;
private List<WeatherEntity> weather;
public void setRequest(List<RequestEntity> request) {
this.request = request;
}
public void setCurrent_condition(List<Current_conditionEntity> current_condition) {
this.current_condition = current_condition;
}
public void setWeather(List<WeatherEntity> weather) {
this.weather = weather;
}
public List<RequestEntity> getRequest() {
return request;
}
public List<Current_conditionEntity> getCurrent_condition() {
return current_condition;
}
public List<WeatherEntity> getWeather() {
return weather;
}
public class RequestEntity {
/**
* query : Rajkot, India
* type : City
*/
private String query;
private String type;
public void setQuery(String query) {
this.query = query;
}
public void setType(String type) {
this.type = type;
}
public String getQuery() {
return query;
}
public String getType() {
return type;
}
}
public class Current_conditionEntity {
private String precipMM;
private String observation_time;
private List<WeatherDescEntity> weatherDesc;
private String visibility;
private String weatherCode;
private String pressure;
private String temp_C;
private String cloudcover;
private String temp_F;
private String winddirDegree;
private String windspeedMiles;
private String windspeedKmph;
private String humidity;
private String winddir16Point;
private List<WeatherIconUrlEntity> weatherIconUrl;
public void setPrecipMM(String precipMM) {
this.precipMM = precipMM;
}
public void setObservation_time(String observation_time) {
this.observation_time = observation_time;
}
public void setWeatherDesc(List<WeatherDescEntity> weatherDesc) {
this.weatherDesc = weatherDesc;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public void setWeatherCode(String weatherCode) {
this.weatherCode = weatherCode;
}
public void setPressure(String pressure) {
this.pressure = pressure;
}
public void setTemp_C(String temp_C) {
this.temp_C = temp_C;
}
public void setCloudcover(String cloudcover) {
this.cloudcover = cloudcover;
}
public void setTemp_F(String temp_F) {
this.temp_F = temp_F;
}
public void setWinddirDegree(String winddirDegree) {
this.winddirDegree = winddirDegree;
}
public void setWindspeedMiles(String windspeedMiles) {
this.windspeedMiles = windspeedMiles;
}
public void setWindspeedKmph(String windspeedKmph) {
this.windspeedKmph = windspeedKmph;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public void setWinddir16Point(String winddir16Point) {
this.winddir16Point = winddir16Point;
}
public void setWeatherIconUrl(List<WeatherIconUrlEntity> weatherIconUrl) {
this.weatherIconUrl = weatherIconUrl;
}
public String getPrecipMM() {
return precipMM;
}
public String getObservation_time() {
return observation_time;
}
public List<WeatherDescEntity> getWeatherDesc() {
return weatherDesc;
}
public String getVisibility() {
return visibility;
}
public String getWeatherCode() {
return weatherCode;
}
public String getPressure() {
return pressure;
}
public String getTemp_C() {
return temp_C;
}
public String getCloudcover() {
return cloudcover;
}
public String getTemp_F() {
return temp_F;
}
public String getWinddirDegree() {
return winddirDegree;
}
public String getWindspeedMiles() {
return windspeedMiles;
}
public String getWindspeedKmph() {
return windspeedKmph;
}
public String getHumidity() {
return humidity;
}
public String getWinddir16Point() {
return winddir16Point;
}
public List<WeatherIconUrlEntity> getWeatherIconUrl() {
return weatherIconUrl;
}
public class WeatherDescEntity {
/**
* value : Sunny
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class WeatherIconUrlEntity {
/**
* value : http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
public class WeatherEntity {
private String date;
private String precipMM;
private List<WeatherDescEntity> weatherDesc;
private String tempMinF;
private String weatherCode;
private String tempMinC;
private String winddirection;
private String winddirDegree;
private String windspeedMiles;
private String windspeedKmph;
private String tempMaxF;
private String winddir16Point;
private List<WeatherIconUrlEntity> weatherIconUrl;
private String tempMaxC;
public void setDate(String date) {
this.date = date;
}
public void setPrecipMM(String precipMM) {
this.precipMM = precipMM;
}
public void setWeatherDesc(List<WeatherDescEntity> weatherDesc) {
this.weatherDesc = weatherDesc;
}
public void setTempMinF(String tempMinF) {
this.tempMinF = tempMinF;
}
public void setWeatherCode(String weatherCode) {
this.weatherCode = weatherCode;
}
public void setTempMinC(String tempMinC) {
this.tempMinC = tempMinC;
}
public void setWinddirection(String winddirection) {
this.winddirection = winddirection;
}
public void setWinddirDegree(String winddirDegree) {
this.winddirDegree = winddirDegree;
}
public void setWindspeedMiles(String windspeedMiles) {
this.windspeedMiles = windspeedMiles;
}
public void setWindspeedKmph(String windspeedKmph) {
this.windspeedKmph = windspeedKmph;
}
public void setTempMaxF(String tempMaxF) {
this.tempMaxF = tempMaxF;
}
public void setWinddir16Point(String winddir16Point) {
this.winddir16Point = winddir16Point;
}
public void setWeatherIconUrl(List<WeatherIconUrlEntity> weatherIconUrl) {
this.weatherIconUrl = weatherIconUrl;
}
public void setTempMaxC(String tempMaxC) {
this.tempMaxC = tempMaxC;
}
public String getDate() {
return date;
}
public String getPrecipMM() {
return precipMM;
}
public List<WeatherDescEntity> getWeatherDesc() {
return weatherDesc;
}
public String getTempMinF() {
return tempMinF;
}
public String getWeatherCode() {
return weatherCode;
}
public String getTempMinC() {
return tempMinC;
}
public String getWinddirection() {
return winddirection;
}
public String getWinddirDegree() {
return winddirDegree;
}
public String getWindspeedMiles() {
return windspeedMiles;
}
public String getWindspeedKmph() {
return windspeedKmph;
}
public String getTempMaxF() {
return tempMaxF;
}
public String getWinddir16Point() {
return winddir16Point;
}
public List<WeatherIconUrlEntity> getWeatherIconUrl() {
return weatherIconUrl;
}
public String getTempMaxC() {
return tempMaxC;
}
public class WeatherDescEntity {
/**
* value : Sunny
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class WeatherIconUrlEntity {
/**
* value : http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
}
}
Response.getData() is DataEntity .You cast it to List<DataEntity>

Android not creating file

I want this fragment to write to a csv file when a button is clicked but I keep getting java.io.IOException: open failed:ENOENT (No such file or directory). Any help would be greatly appreciated.
public class AddFragment extends Fragment {
static EditText spent,saved,coupons;
Button writeExcelButton;
String data;
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_layout, container, false);
setSpinnerContent(view);
spent = (EditText) view.findViewById(R.id.spent1);
saved = (EditText) view.findViewById(R.id.saved1);
coupons = (EditText) view.findViewById(R.id.coupons1);
writeExcelButton = (Button) view.findViewById(R.id.button_addGroc);
writeExcelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateSheet();
}
});
return view;
}
private void setSpinnerContent (View view) {
spinner = (Spinner) view.findViewById(R.id.groc_store);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.store1, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void updateSheet() {
try {
// This is the string that should be written to file
String mySpin =spinner.getSelectedItem().toString();
data = mySpin + "," + spent.getText().toString() + "," + saved.getText().toString() + "," + coupons.getText().toString() + "/n";
// This is the file that should be written to
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
if (!dir.exists()) {
dir.mkdir();
}
File myFile = new File(dir.getAbsolutePath(), "savings.csv");
// if file doesn't exists, then create it
if (!myFile.exists()) {
myFile.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is what my LogCat looks like
11-14 13:29:23.681: W/System.err(14386): java.io.IOException: open failed: ENOENT (No such file or directory)
11-14 13:29:23.681: W/System.err(14386): at java.io.File.createNewFile(File.java:948)
11-14 13:29:23.691: W/System.err(14386): at com.example.myfirstapp.AddFragment.updateSheet(AddFragment.java:101)
11-14 13:29:23.691: W/System.err(14386): at com.example.myfirstapp.AddFragment$1.onClick(AddFragment.java:59)
11-14 13:29:23.691: W/System.err(14386): at android.view.View.performClick(View.java:4240)
11-14 13:29:23.691: W/System.err(14386): at android.view.View$PerformClick.run(View.java:17721)
11-14 13:29:23.691: W/System.err(14386): at android.os.Handler.handleCallback(Handler.java:730)
11-14 13:29:23.691: W/System.err(14386): at android.os.Handler.dispatchMessage(Handler.java:92)
11-14 13:29:23.691: W/System.err(14386): at android.os.Looper.loop(Looper.java:137)
11-14 13:29:23.691: W/System.err(14386): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-14 13:29:23.691: W/System.err(14386): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 13:29:23.691: W/System.err(14386): at java.lang.reflect.Method.invoke(Method.java:525)
11-14 13:29:23.701: W/System.err(14386): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-14 13:29:23.711: W/System.err(14386): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 13:29:23.711: W/System.err(14386): at dalvik.system.NativeStart.main(Native Method)
11-14 13:29:23.711: W/System.err(14386): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
11-14 13:29:23.711: W/System.err(14386): at libcore.io.Posix.open(Native Method)
11-14 13:29:23.711: W/System.err(14386): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
11-14 13:29:23.711: W/System.err(14386): at java.io.File.createNewFile(File.java:941)
Try changing
dir.mkdir();
to
dir.mkdirs();
Also try just passing dir instead of dir.getAbsolutePath()
Edit
Also you don't want to concatanate file paths like that. Try:
File myFile = new File(Environment.getExternalStorageDirectory(), "dir/savings.csv");
if (!myFile.exists()) {
myFile.mkdirs();
myFile.createNewFile();
}
Add this permissions in manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android App crashes right on start

I have an app that's supposed to get some string from a server depending on the webpage, and it crashes every time I run it. I don't understand how to even debug it, and I've tried numerous changes. It started crashing ever since I messed with the GUI, and added the ability to switch views if that provides any sort of help.
Here is the code:
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener{
private WebView mWebview;
EditText addressBar;
String currentWebpage = "http://www.aljazeera.com/news/americas/2013/07/20137113200544375.html";
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
View main = (View) findViewById(R.layout.activity_main);
View readOut = (View) findViewById(R.layout.read_out);
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("Showing Activity_Main...");
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
super.onCreate(savedInstanceState);
//setContentView(R.menu.main);
addressBar = (EditText)findViewById(R.id.addressBar);
addressBar.setText(currentWebpage);
mWebview = (WebView)findViewById(R.id.webview);
mWebview.getSettings().setJavaScriptEnabled(true); // enables javascript
mWebview.setWebViewClient(new WebViewClient());
System.out.println("Loading Webpage...");
mWebview.loadUrl(currentWebpage);
}
public void speakOut(String text) {
TextToSpeech tts = new TextToSpeech(this, this);
System.out.println("Speaking");
if(tts.isLanguageAvailable(Locale.ENGLISH) != -1){
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public int speakFull(String text){
switchToRead();
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
speakOut(sentences[i]);
if(i == sentences.length - 1){
return 1;
}
}
return 0;
}
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://someserver.net:8080/" + webPage));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
private class tts extends AsyncTask<String, Void, String>{//Async http request to get text
#Override
protected String doInBackground(String... arg0) {
try {
System.out.println("Running seperate thread for TTS.");
int complete = 0;
while(complete == 0){
System.out.println("Speaking full..");
complete = speakFull(getText(mWebview.getUrl()));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
}
}
public void clickPlay(View v){
new tts().execute("");
}
public void clickGo(View v){
if(addressBar.getText() != null){
currentWebpage = addressBar.getText().toString();
System.out.println("Current webpage changed to: " + currentWebpage);
mWebview.loadUrl(currentWebpage);
}
}
public void clickPause(View v){
System.out.println("Clicked pause.");
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
System.out.println("Swtiching view to Read.");
viewGroup.removeView(main);
viewGroup.addView(View.inflate(this, R.layout.read_out, null));
}
public void switchToMain(){
System.out.println("Switching view to Main.");
viewGroup.removeView(readOut);
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
}
}
Also here are the numerous errors I encounter when launching my app:
08-01 14:53:10.210: E/Trace(812): error opening trace file: No such file or directory (2)
08-01 14:53:10.600: D/AndroidRuntime(812): Shutting down VM
08-01 14:53:10.631: W/dalvikvm(812): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:10.660: E/AndroidRuntime(812): FATAL EXCEPTION: main
08-01 14:53:10.660: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:10.660: E/AndroidRuntime(812): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): Caused by: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:10.660: E/AndroidRuntime(812): ... 11 more
08-01 14:53:27.439: D/AndroidRuntime(860): Shutting down VM
08-01 14:53:27.439: W/dalvikvm(860): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:27.449: E/AndroidRuntime(860): FATAL EXCEPTION: main
08-01 14:53:27.449: E/AndroidRuntime(860): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:27.449: E/AndroidRuntime(860): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): Caused by: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:27.449: E/AndroidRuntime(860): ... 11 more
Move your view initialization inside onCreate after setContentView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
...// rest of the code

Android app crash when try to overwrite text in a TextView from other class

I try to change 3 textviews in a class called UserProfile() calling the method update() from the class UpdateProfile(), the class UserProfile do something like this:
package com.safm;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class UserProfile extends Activity {
TextView username, usersurname, useremail;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
username = (TextView) findViewById(R.id.username);
usersurname = (TextView) findViewById(R.id.usersurname);
useremail = (TextView) findViewById(R.id.useremail);
}
public void updateButton(View view){
Intent i = new Intent(this, UpdateProfile.class);
startActivity(i);
}
public void update(String nname, String nusername, String nemail){
System.out.println("2");
System.out.println(nname);
username.setText(nname);
usersurname.setText(nusername);
useremail.setText(nemail);
System.out.println("3");
}
}
The updateButton method invoke the UpdateProfile class:
package com.safm;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateProfile extends Activity {
EditText newusernametxt, newsurnametxt, newemailtxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actualizarperfil);
newusernametxt = (EditText) findViewById(R.id.newusernametxt);
newsurnametxt = (EditText) findViewById(R.id.newsurnametxt );
newemailtxt = (EditText) findViewById(R.id.newemailtxt );
}
public void updateInfo(View view){
String nname = newusernametxt .getText().toString();
String nsurname = newsurnametxt .getText().toString();
String nemail = newemailtxt .getText().toString();
if(nname.compareTo("") != 0 && nsurname.compareTo("") != 0 && nemail.compareTo("") != 0){
UserProfile profile = new UserProfile();
System.out.println("1");
profile.update(nname, nsurname, nemail);
System.out.println("4");
Toast.makeText(this, "Success, the profile has been updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "You can't empty fields", Toast.LENGTH_SHORT).show();
}
}
This is my logcat file, as you can see, the first 2 flags are printed correctly, the error is when I try to set another text on the TextView, but the value of the strings (nname, nsurname and nemail) are not empty cause also is printed in the console HELP!
05-14 21:43:31.140: I/System.out(878): 1
05-14 21:43:31.140: I/System.out(878): 2
05-14 21:43:31.150: I/System.out(878): TextEditValue
05-14 21:43:31.150: D/AndroidRuntime(878): Shutting down VM
05-14 21:43:31.150: W/dalvikvm(878): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-14 21:43:31.310: E/AndroidRuntime(878): FATAL EXCEPTION: main
05-14 21:43:31.310: E/AndroidRuntime(878): java.lang.IllegalStateException: Could not execute method of the activity
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$1.onClick(View.java:3599)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View.performClick(View.java:4204)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$PerformClick.run(View.java:17355)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Handler.handleCallback(Handler.java:725)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:137)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 21:43:31.310: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): Caused by: java.lang.reflect.InvocationTargetException
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$1.onClick(View.java:3594)
05-14 21:43:31.310: E/AndroidRuntime(878): ... 11 more
05-14 21:43:31.310: E/AndroidRuntime(878): Caused by: java.lang.NullPointerException
05-14 21:43:31.310: E/AndroidRuntime(878): at com.safm.UserProfile.update(UserProfile.java:31)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.safm.UserProfile.updateInfo(UpdateProfile.java:33)
05-14 21:43:31.310: E/AndroidRuntime(878): ... 14 more
NOTE: I've clean the project and defined the TextView in ProfileUser class and the TextEdit in UpdateProfile outside the onCreate method but doesn't work.
Thanks.
Activities in Android are separate containers, that are in no way allowed to directly touch eachother. This is because the application stack behind Android 'freezes' the activities when they are no longer on the foreground, and could even be swapped to hard storage to save on RAM at the operating system's discretion.
Your UserProfile encapsulation should just reload its data after the UpdateProfile activity is closed, or request communication back the proper way via startActivityForResult.
Your current implementation is technically incorrect from each perspective, since you're hardcoding the UpdateProfile activity to always be called from a UserProfile activity. What if some day you introduce a new menu option to call it directly from the home screen? Activities are always separate, and should not make such assumptions.

Categories