Im attempting to connect to a database via a backgroundtask via a tab but it does not like it. Can you guys see what the issue is, as I used same code in another project and worked fine..
public class Tab2Activity extends Activity
{
SharedPreferences preferences;
String driver;
String task;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab2);
preferences = getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
TextView name = (TextView) findViewById (R.id.textView1);
// dummy data to send
task="login";
driver="2";
// create and call background activity
BackgroundTask backgroundTask = new BackgroundTask(Tab2Activity.this);
backgroundTask.execute(task,driver);
//get data back from sharedpreference
String mName = preferences.getString("myData","ERROR getting name");
//display data
name.setText(mName);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tab2, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the backGroundTask code
public class BackgroundTask extends AsyncTask<String,Void,String>
{
SharedPreferences preferences;
SharedPreferences.Editor editor;
SharedPreferences.Editor pig;
Context context;
BackgroundTask(Context ctx)
{
this.context = ctx;
}
#Override
protected String doInBackground(String... params)
{
preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.putString("flag","0");
editor.commit();
String urlLogin = "http://Domain.com/GetJobs.php";
String task = params[0];
String driver_id_app = params[1];
try {
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the driver number to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myData = URLEncoder.encode("driver_id","UTF-8")+"="+URLEncoder.encode(driver_id_app,"UTF-8");
//+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8");
bufferedWriter.write(myData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null){
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
///System.out.println(dataResponse);
editor.putString("flag","login");
editor.commit();
pig = preferences.edit();
pig.putString("myData",dataResponse);
pig.commit();
return dataResponse;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
public void display(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
These are the error logs
01-21 23:28:26.074: E/AndroidRuntime(27426): FATAL EXCEPTION: AsyncTask #3
01-21 23:28:26.074: E/AndroidRuntime(27426): Process: com.example.tabdemo, PID: 27426
01-21 23:28:26.074: E/AndroidRuntime(27426): java.lang.RuntimeException: An error occurred while executing doInBackground()
01-21 23:28:26.074: E/AndroidRuntime(27426): at android.os.AsyncTask$3.done(AsyncTask.java:309)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-21 23:28:26.074: E/AndroidRuntime(27426): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.lang.Thread.run(Thread.java:818)
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.lookupHostByName(InetAddress.java:464)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.getAllByName(InetAddress.java:215)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:220)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:176)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:108)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:482)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:465)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:447)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:353)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.example.tabdemo.BackgroundTask.doInBackground(BackgroundTask.java:63)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.example.tabdemo.BackgroundTask.doInBackground(BackgroundTask.java:1)
01-21 23:28:26.074: E/AndroidRuntime(27426): at android.os.AsyncTask$2.call(AsyncTask.java:295)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-21 23:28:26.074: E/AndroidRuntime(27426): ... 4 more
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
01-21 23:28:26.074: E/AndroidRuntime(27426): at libcore.io.Posix.android_getaddrinfo(Native Method)
01-21 23:28:26.074: E/AndroidRuntime(27426): at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
01-21 23:28:26.074: E/AndroidRuntime(27426): ... 21 more
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: android.system.ErrnoException: android_getaddrinfo failed: EACCES (Permission denied)
01-21 23:28:26.074: E/AndroidRuntime(27426): ... 24 more
Really hope you guys can suggest something...
I can clearly see that you are missing the internet connection permission.
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
You need to add this in your manifest to enable internet connection:
<uses-permission android:name="android.permission.INTERNET" />
Related
I got this error whenever I change my URL to my online hosting, but if I change to 10.0.2.2 everything seems fine and running.
LogCat
02-01 23:02:18.302 17643-18052/com.example.jithea.testlogin E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0x40d8d9a8)
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: uncaught exception occurred
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ java.lang.RuntimeException: An error occured while executing doInBackground()
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ Caused by: java.lang.NullPointerException
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ ... 4 more
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: calling UncaughtExceptionHandler
02-01 23:02:18.315 17643-18052/com.example.jithea.testlogin E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.371 17643-17659/com.example.jithea.testlogin I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x528dc150) fps:43.08, dur:1044.57, max:73.51, min:6.02
And here's my NewsActivity.java
public class NewsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParserNews jParser = new JSONParserNews();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://agustiniancampusevents.site40.net/newsDB/get_all_news.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_PID = "pid";
private static final String TAG_NEWSTITLE = "newstitle";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_NEWS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String newstitle = c.getString(TAG_NEWSTITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NEWSTITLE, newstitle);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NewsActivity.this, productsList,
R.layout.news_list_item, new String[]{TAG_PID,
TAG_NEWSTITLE},
new int[]{R.id.pid, R.id.newstitle});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I have a php/mysql query working that looks up the VIN, if the VIN is in the database it returns "VIN already exists" Where did I screw up in this: Error report say Fatal Exception : AsyncTask #2 (I have code that actually works above this, problem started when I tried to rewrite this to run the php checkVin before launching the Sell page)
11-21 16:34:43.736: E/AndroidRuntime(725): FATAL EXCEPTION: AsyncTask #2
11-21 16:34:43.736: E/AndroidRuntime(725): java.lang.RuntimeException: An error occured while executing doInBackground()
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.lang.Thread.run(Thread.java:856)
11-21 16:34:43.736: E/AndroidRuntime(725): Caused by: java.lang.IllegalArgumentException: Host name may not be null
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:626)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.getServerResopnse(Scan.java:272)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.access$1(Scan.java:260)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:240)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:1)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-21 16:34:43.736: E/AndroidRuntime(725): ... 5 more
private void addSellButtonListener() {
Button sell = (Button) findViewById(R.id.sell_button);
sell.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendDatatoServer();
}
});
}
private String formatDataAsJASON() {
JSONObject root = new JSONObject();
try {
root.put("User", userId.getText().toString());
root.put("Pword", userPass.getText().toString());
root.put("VIN", VINID.getText().toString());
return root.toString();
} catch (JSONException e) {
Log.d("JWP", "Can't format JSON");
}
return null;
}
private void sendDatatoServer() {
final String json = formatDataAsJASON();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
return getServerResopnse(json);
}
#Override
protected void onPostExecute(String result) {
if (result == "VIN already exists") {
Toast.makeText(Scan.this,
getString(R.string.vin_exists), Toast.LENGTH_LONG)
.show();
final Intent i = new Intent(Scan.this, Scan.class);
startActivity(i);
} else {
StartSell();
}
}
}.execute();
}
private String getServerResopnse(String json) {
HttpPost post = new HttpPost("http://" + serverIp.getText().toString()
+ "/chekVIN.php");
try {
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
return response;
} catch (UnsupportedEncodingException e) {
Log.d("JWP", e.toString());
} catch (ClientProtocolException e) {
Log.d("JWP", e.toString());
} catch (IOException e) {
Log.d("JWP", e.toString());
}
return null;
}
private void StartSell() {
final Intent i = new Intent(Scan.this, Sell.class);
EditText editText = (EditText) findViewById(R.id.VIN);
String text = editText.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.Make);
String text2 = editText2.getText().toString();
EditText editText3 = (EditText) findViewById(R.id.Model);
String text3 = editText3.getText().toString();
EditText editText4 = (EditText) findViewById(R.id.Color);
String text4 = editText4.getText().toString();
EditText editText5 = (EditText) findViewById(R.id.Year);
String text5 = editText5.getText().toString();
try {
FileOutputStream fos = openFileOutput(VinHolder,
Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
FileOutputStream fos2 = openFileOutput(MakeHolder,
Context.MODE_PRIVATE);
fos2.write(text2.getBytes());
fos2.close();
FileOutputStream fos3 = openFileOutput(ModelHolder,
Context.MODE_PRIVATE);
fos3.write(text3.getBytes());
fos3.close();
FileOutputStream fos4 = openFileOutput(ColorHolder,
Context.MODE_PRIVATE);
fos4.write(text4.getBytes());
fos4.close();
FileOutputStream fos5 = openFileOutput(YearHolder,
Context.MODE_PRIVATE);
fos5.write(text5.getBytes());
fos5.close();
}
catch (Exception e) {
Log.d("DEBUGTAG", "File Not Saved" + text);
e.printStackTrace();
}
startActivity(i);
}
Because I use a Text file from another page of the app to hold a manually entered ip address, I needed to carry that info over so that the the HttpPost("http://" +serverIp.getText().toString() + "chechvin.php"); would actually have the ip address in it.
After adding:
public static final String SERVERIP= "sinfo.txt";
everything worked just fine.
I am new to android. I have created an app which was a pull parser in order to extract items from an Rss feed, into a ListView. Unfortunately my app seems to force close when I try and place code in order implement some sort of filtering mechanism in my ListView. This is the code I have so far, and I have no idea why it seems to crash. Any help would be appreciated.
public class RssFeed extends ListActivity {
// Listview Adapter
ArrayAdapter<string> adapter;
EditText SearchBox;
List titles;
public static List description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss);
// Initialising instance variables
titles = new ArrayList();
description = new ArrayList();
try {
URL url = new URL("http://my.url");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
/** While the rss feed has not displayed end_document, pull the title and description information */
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
titles.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
description.add(xpp.nextText());
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
SearchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
RssFeed.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
And the LogCat:
04-12 20:43:00.792: D/dalvikvm(324): GC freed 7597 objects / 316440 bytes in 88ms
04-12 20:43:00.852: D/AndroidRuntime(324): Shutting down VM
04-12 20:43:00.852: W/dalvikvm(324): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-12 20:43:00.852: E/AndroidRuntime(324): Uncaught handler: thread main exiting due to uncaught exception
04-12 20:43:00.862: E/AndroidRuntime(324): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff.simpleRssReader/org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed}: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Looper.loop(Looper.java:123)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invoke(Method.java:521)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-12 20:43:00.862: E/AndroidRuntime(324): at dalvik.system.NativeStart.main(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): Caused by: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed.onCreate(RssFeed.java:142)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-12 20:43:00.862: E/AndroidRuntime(324): ... 11 more
04-12 20:43:00.892: I/dalvikvm(324): threadid=7: reacting to signal 3
04-12 20:43:00.892: E/dalvikvm(324): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
First of all: the class you posted doesn't have 142 lines, be sure to post the whole class.
Second: SearchBox is null here.
That is because you declared it with
EditText SearchBox;
but never assigned it which you would usually do from your layout like
SearchBox = (EditText) findViewById(R.id.searchBox);
(just an example)
SeachBox does not have an assigned value at this point so you can't use any methods on it.
Third: Use lower case names like searchBox, it'll make your code easier to read for others and yourself.
I'm debugging an Asynctask that simply downloads a file: here the code:
public class AsyncDownloadFilesTask extends AsyncTask<String, Integer, Boolean> {
public AsyncResponse<Boolean> delegate=null;
protected Boolean doInBackground(String... params) {
android.os.Debug.waitForDebugger();
try {
URL url = new URL(params[0]);
int count;
String fileName = new String(params[1]);
URLConnection connessione = url.openConnection();
connessione.connect();
int lenghtOfFile = connessione.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileName);
long total = 0;
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return Boolean.valueOf(true);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Boolean result) {
delegate.processFinish(result);
}
}
I obtain a strange behaviour: when execution arrive to return
Boolean.valueOf(true);
it skips to
return null;
into the catch block, but Exception e is null, and then debugger goto line 1 of AsyncTask, that is simply
package com.example.compa.asynctasks;
Then execution goes on (executing onPostExecute method) and, of course, returned result is null
What happens? Why debug jump in this way?
Task download correctly the file.
Here code of the Activity that instantiates and calls Async Task
package com.example.compa.activities;
import android.app.Activity;
import ...
public class CoverActivity extends Activity implements AsyncResponse<Boolean>{
ImageView coverImg;
Drawable d;
CompassesFileManager cfm;
int coverId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cover);
coverId = getIntent().getExtras().getInt("coverId");
cfm = new CompassesFileManager(this);
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
d = cfm.getCover(coverId);
if (d!=null){
coverImg.setImageDrawable(d);
} else {
AsyncDownloadFilesTask task = new AsyncDownloadFilesTask();
task.delegate = this;
task.execute(cfm.getCoverURL(coverId), cfm.getCoverFileName(coverId));
}
}
#Override
public void processFinish(Boolean output) {
if (output){
Drawable d = cfm.getCover(coverId);
coverImg.setImageDrawable(d);
} else {
finish();
}
}
}
Stacktrace of error:
02-21 19:37:29.520: E/AndroidRuntime(407): FATAL EXCEPTION: main
02-21 19:37:29.520: E/AndroidRuntime(407): java.lang.NullPointerException
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:1)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Looper.loop(Looper.java:176)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-21 19:37:29.520: E/AndroidRuntime(407): at dalvik.system.NativeStart.main(Native Method)
line:
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
is the last one of AsyncDownloadFilesTask class, and is a closing bracket, }
Thank you
I don't have enough points to comment, but it looks like delegate is null in your onPostExecute
delegate.processFinish(result); // delegate is null
if that's not the case, you're code stub above doesn't define it though.
I solved on my own.
1st, I move call to the Async Task in the onStart() method, instead of onCreate()
2nd, I made a mistake, in change line
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
in
coverImg = (ImageView)findViewById(R.id.cover_image);
to avoid a stupid null pointer (I already declared coverImg)!
Anyway, I still don't understand debug's behaviour, but I solved my problem.
Thank you everybody
I have the following Fragment. It works completely fine, until I rotate my device. It then crashes with errors about the RadarSelectionFragment failing to Instantiate. The code for the FragmentPagerAdapter and the Fragment in question are below:
#SuppressLint("DefaultLocale")
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter() {
// Do some stuff
}
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Fragment fragment = new RadarSelectionFragment();
Bundle args = new Bundle();
args.putInt(RadarSelectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
} else if (position == 1) {
Fragment fragment = new WeatherMapDisplayFragment();
Bundle args = new Bundle();
args.putInt(WeatherMapDisplayFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
} else {
Fragment tf = new RadarSelectionFragment();
return tf;
}
}
#Override
public int getCount() {
return 2;
}
#SuppressLint("DefaultLocale")
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
}
return null;
}
}
public static class RadarSelectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public RadarSelectionFragment() {}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
return inflater.inflate(R.layout.radars, container, false);
} else {
return container;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
...
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
}
}
public class WeatherMapDisplayFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public WeatherMapDisplayFragment() {
}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
return inflater.inflate(R.layout.display, container, false);
} else {
return container;
}
}
}
I have tried Googling the problem, but all I keep turning up are various solutions pertaining to ensuring that the Fragment Class is static (Which I've done).
I am relatively new to Android programming, so if you answer, could you please either post an example and/or link to other examples if you have the time.
Thanks in advance!
EDIT 1: Stacktrace
01-21 13:46:31.907: E/AndroidRuntime(1101): FATAL EXCEPTION: main
01-21 13:46:31.907: E/AndroidRuntime(1101): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.radarau/com.example.radarau.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3692)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.access$700(ActivityThread.java:141)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.os.Looper.loop(Looper.java:137)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.reflect.Method.invokeNative(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.reflect.Method.invoke(Method.java:511)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-21 13:46:31.907: E/AndroidRuntime(1101): at dalvik.system.NativeStart.main(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.Fragment.instantiate(Fragment.java:405)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1767)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:208)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.example.radarau.MainActivity.onCreate(MainActivity.java:35)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.Activity.performCreate(Activity.java:5104)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-21 13:46:31.907: E/AndroidRuntime(1101): ... 12 more
01-21 13:46:31.907: E/AndroidRuntime(1101): Caused by: java.lang.InstantiationException: can't instantiate class com.example.radarau.MainActivity$WeatherMapDisplayFragment; no empty constructor
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.Class.newInstanceImpl(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.Class.newInstance(Class.java:1319)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
01-21 13:46:31.907: E/AndroidRuntime(1101): ... 19 more
Your logcat says
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
You should provide a public Default constructor for that
public WeatherMapDisplayFragment() {
// Do some stuff
}
If that class is nested, make that class to static class and provide a public default constructor or move that fragment into a new java file.