Error converting http entity result java.lang.NullPointerException: lock == null - java

I am new to develop an android application. I have read a lot of related post regarding the question I was asking but the tips or solution from the post did not solve my problem. (Looking for the solution for a week already, really need help in order to proceed with my project) Thanks a lot...
Error line No 121
Image LinK
update.java:
package pounkumarpurushothaman.ghssvmm;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class update extends ActionBarActivity {
public static final String KEY_121 ="http://ghssvmm.site40.net/update.php";
static Activity thisActivity = null;
InputStream is = null;
// LinearLayout yy=(LinearLayout)findViewById(R.id.uy);
// LinearLayout pp=(LinearLayout)findViewById(R.id.up);
//LinearLayout cc=(LinearLayout)findViewById(R.id.uc);
//LinearLayout ca=(LinearLayout)findViewById(R.id.uca);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getServerData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_update, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getServerData() {
thisActivity=this;
EditText f = (EditText) findViewById(R.id.ufst);
EditText l = (EditText) findViewById(R.id.ulst);
Spinner bld=(Spinner)findViewById(R.id.ubld);
Spinner stat=(Spinner)findViewById(R.id.ustatus);
Spinner bth=(Spinner)findViewById(R.id.ubat);
EditText dob = (EditText) findViewById(R.id.udob);
EditText phn1 = (EditText) findViewById(R.id.uphn);
EditText phn2 = (EditText) findViewById(R.id.uphn2);
EditText padd = (EditText) findViewById(R.id.upadd);
EditText radd = (EditText) findViewById(R.id.uradd);
EditText vill = (EditText) findViewById(R.id.uvill);
Spinner sec=(Spinner)findViewById(R.id.usec);
Spinner deg=(Spinner)findViewById(R.id.udeg);
EditText dept = (EditText) findViewById(R.id.udept);
EditText clg = (EditText) findViewById(R.id.uclg);
EditText yop = (EditText) findViewById(R.id.uyop);
EditText pos = (EditText) findViewById(R.id.upos);
EditText cmp = (EditText) findViewById(R.id.ucom);
EditText cadd = (EditText) findViewById(R.id.ucaddr);
String result = "";
//the year data to send
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email","abc#gmail.com"));
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(thisActivity, "Error in http connection " + e.toString(),Toast.LENGTH_LONG).show();
}
}
});
thread.start();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Toast.makeText(this, "Error converting result "+e.toString(),Toast.LENGTH_LONG).show();
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
f.setText(json_data.getString("fname"));
l.setText(json_data.getString("lname"));
dob.setText(json_data.getString("dob"));
switch(json_data.getString("blood")){
case "O Positive":
bld.setSelection(1);
break;
case "O Negative":
bld.setSelection(2);
break;
case "A Positive":
bld.setSelection(3);
break;
case "A Negative":
bld.setSelection(4);
break;
case "B Positive":
bld.setSelection(5);
break;
case "B Negative":
bld.setSelection(6);
break;
case "AB Positive":
bld.setSelection(7);
break;
case "AB Negative":
bld.setSelection(8);
break;
}
switch(json_data.getString("section")) {
case "A":
sec.setSelection(1);
break;
case "B":
sec.setSelection(2);
break;
case "C":
sec.setSelection(3);
break;
}
phn1.setText(json_data.getString("phn"));
phn2.setText(json_data.getString("phn2"));
padd.setText(json_data.getString("add"));
radd.setText(json_data.getString("add2"));
switch(json_data.getString("status")) {
case "Student":
stat.setSelection(1);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.INVISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
case "Employee":
stat.setSelection(2);
/*cc.setVisibility(View.VISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.VISIBLE);
ca.setVisibility(View.VISIBLE);*/
break;
case "Un Employee":
stat.setSelection(3);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
}
switch(json_data.getString("degree")) {
case "B.E":
deg.setSelection(1);
break;
case "Arts and Science":
deg.setSelection(2);
break;
case "Medical":
deg.setSelection(3);
break;
}
dept.setText(json_data.getString("dept"));
clg.setText(json_data.getString("clg"));
yop.setText(json_data.getString("yop"));
pos.setText(json_data.getString("pos"));
cmp.setText(json_data.getString("com"));
cadd.setText(json_data.getString("caddr"));
vill.setText(json_data.getString("vill"));
//Get an output to the screen
}
}catch(JSONException e) {
Toast.makeText(this, "Error parsing data " + e.toString(), Toast.LENGTH_LONG).show();
}
}
}
**
Logcat :
**
04-06 14:11:39.580 25919-25919/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: pounkumarpurushothaman.ghssvmm, PID: 25919
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{pounkumarpurushothaman.ghssvmm/pounkumarpurushothaman.ghssvmm.update}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2081)
at pounkumarpurushothaman.ghssvmm.update.<init>(update.java:34)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
.

Here's how you get response after your POST request is executed .
HttpResponse response = httpClient.execute(httpPost);
String op = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.d("Response:", op);

Related

Error fetching resources from assests folder

I have recently started a new project, at the moment I am trying to create a SQLite database from within the main activity and read from a text file located in my assests folder. Here is my code:
package com.example.kingmarkmcc.universe;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private Button simulator;
private Button helper;
private Button settings;
private Button milkyway;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
if (v == simulator) {
Intent intent = new Intent(MainActivity.this, Simulator.class);
startActivity(intent);
} else if (v == helper) {
Intent intent = new Intent(MainActivity.this, HelpOptions.class);
startActivity(intent);
} else if (v == settings) {
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this, MilkyWay.class);
startActivity(intent);
}
}
};
simulator = (Button) findViewById(R.id.buttonr1b1);
simulator.setOnClickListener(listener);
helper = (Button) findViewById(R.id.buttonr1b2);
helper.setOnClickListener(listener);
settings = (Button) findViewById(R.id.buttonr2b1);
settings.setOnClickListener(listener);
milkyway = (Button) findViewById(R.id.buttonr2b2);
milkyway.setOnClickListener(listener);
}
#Override
protected void onStart()
{
super.onStart();
MainActivity myMain = new MainActivity();
myMain.createDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void createDB(){
SQLiteDatabase db= null;
final String dbName = "starDB";
final String tableName = "starTable";
String[] rowRead;
String line;
try {
InputStream input;
input = getAssets().open("refinedData.txt");
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader bufferReader = new BufferedReader(inputReader);
//Retrieve or create DataBase
db = this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
//Creating table
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ tableName
+ " (id INTEGER, proper TEXT, dist INTEGER , absmag INTEGER , spect TEXT , ci INTEGER , x INTEGER , y INTEGER , z INTEGER , vx INTEGER , vy INTEGER , vz INTEGER);");
while((line = bufferReader.readLine())!= null) {
rowRead = line.split(",");
// Put data into table
db.execSQL("INSERT INTO "
+ tableName
+ " (id, proper, dist, absmag, spect, ci, x, y, z, vx, vy, vz)"
+ " VALUES (" + rowRead[0] + "," + rowRead[1] + "," + rowRead[2] + "," + rowRead[3] + "," + rowRead[4] + "," + rowRead[5] + "," + rowRead[6] + "," + rowRead[7] + "," + rowRead[8] + "," + rowRead[9] + "," + rowRead[10] + "," + rowRead[11] + ");");
}
bufferReader.close();
Cursor c = db.rawQuery("SELECT * FROM " + tableName, null);
int Column1 = c.getColumnIndex("id");
int Column2 = c.getColumnIndex("x");
c.moveToFirst();
int id = c.getInt(Column1);
int x = c.getInt(Column2);
System.out.println(id);
System.out.println(x);
Toast.makeText(MainActivity.this, "End", Toast.LENGTH_LONG).show();
}
catch(Exception e) {
Log.e("Error", "Error", e);}
finally {
if (db != null)
db.close();
}
}
This is the error that I am receiving:
02-04 17:41:28.973 27362-27362/com.example.kingmarkmcc.universe D/AndroidRuntime: Shutting down VM
02-04 17:41:28.974 27362-27362/com.example.kingmarkmcc.universe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kingmarkmcc.universe, PID: 27362
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kingmarkmcc.universe/com.example.kingmarkmcc.universe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$900(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at com.example.kingmarkmcc.universe.MainActivity.createDB(MainActivity.java:114)
at com.example.kingmarkmcc.universe.MainActivity.onStart(MainActivity.java:83)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
at android.app.ActivityThread.access$900(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:139) 
at android.app.ActivityThread.main(ActivityThread.java:5298) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
02-04 17:41:28.977 27362-27362/com.example.kingmarkmcc.universe D/AppTracker: App Event: crash
I have tried to correct this error but cannot seem to figure out the problem! Any help would be much appreciated
Your immediate problem is this:
MainActivity myMain = new MainActivity();
Never create your own instances of activities this way. For starters, they do not work, as you are seeing. Besides, you are in an instance of MainActivity. You do not need a second one. Just call createDB().
Also, you are performing a lot of disk I/O on the main application thread. Your UI will be frozen for quite some time as a result. Do not do this. Please move significant disk I/O to a background thread.
Note that it would be faster for your user, and simpler for you as a developer, to use SQLiteAssetHelper, to package a prepared database in your app, rather than do a bunch of SQL statements to accomplish the same thing.

HTTP Request Android - Attempt to invoke virtual method

So I have a problem. I have been trying to get an http request to work for quite a while now, and I have made a new thread so that the request never runs on the main thread. I have successfully made it so that the HTTP Request occurs and in the request thread I have made it so it logs the data that it has grabbed from the http request. Now if I ever want to use this jsonObject outside the method it gives me errors. Help?
LogCat:
02-23 22:48:08.612 4239-4239/com.tamrefrank.www.listviewandroidstudio E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tamrefrank.www.listviewandroidstudio, PID: 4239
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tamrefrank.www.listviewandroidstudio/com.tamrefrank.www.listviewandroidstudio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONArray.toString()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONArray.toString()' on a null object reference
at com.tamrefrank.www.listviewandroidstudio.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-23 22:48:09.332 4239-4254/com.tamrefrank.www.listviewandroidstudio I/log_tag﹕ [{"Name":"Cabinet","Location":"In Storage","Latitude":"40.83990100","Longitude":"14.25185000","pk":19587,"image_id":"2006AJ6728"},{"Name":"Panel","Location":"Medieval and Renaissance, room 8, case WS EXP","Latitude":"48.87287900","Longitude":"4.63710000","pk":11371,"image_id":"2006AP3163"},{"Name":"Wallpaper","Location":"British Galleries, room 122f, case 1","Latitude":"53.47962200","Longitude":"-2.24881000","pk":19492,"image_id":"2006AU6265"},{"Name":"Portrait miniature","Location":"British Galleries, room 58c, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":9491,"image_id":"2006AH0271"},{"Name":"Caricature","Location":"In Storage","Latitude":"53.02513900","Longitude":"-2.18676000","pk":29979,"image_id":"2006AE9142"},{"Name":"Card game","Location":"In Storage","Latitude":"52.88328900","Longitude":"-1.97685000","pk":26483,"image_id":"2006AU5916"},{"Name":"Tile","Location":"Islamic Middle East, room 42, case WW9","Latitude":"39.76586200","Longitude":"64.42234000","pk":30220,"image_id":"2006AY5617"},{"Name":"Sculpture","Location":"Sculpture, room 22, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":36026,"image_id":"2006AM7780"},{"Name":"Oil painting","Location":"Prints & Drawings Study Room, room 315, case 24, shelf R","Latitude":"52.88328900","Longitude":"-1.97685000","pk":6905,"image_id":"2006AU6480"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10895,"image_id":"2006AU8783"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10902,"image_id":"2006AU9234"}]
02-23 22:48:09.332 4239-4254/com.tamrefrank.www.listviewandroidstudio I/log_tag﹕ [{"Name":"Cabinet","Location":"In Storage","Latitude":"40.83990100","Longitude":"14.25185000","pk":19587,"image_id":"2006AJ6728"},{"Name":"Panel","Location":"Medieval and Renaissance, room 8, case WS EXP","Latitude":"48.87287900","Longitude":"4.63710000","pk":11371,"image_id":"2006AP3163"},{"Name":"Wallpaper","Location":"British Galleries, room 122f, case 1","Latitude":"53.47962200","Longitude":"-2.24881000","pk":19492,"image_id":"2006AU6265"},{"Name":"Portrait miniature","Location":"British Galleries, room 58c, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":9491,"image_id":"2006AH0271"},{"Name":"Caricature","Location":"In Storage","Latitude":"53.02513900","Longitude":"-2.18676000","pk":29979,"image_id":"2006AE9142"},{"Name":"Card game","Location":"In Storage","Latitude":"52.88328900","Longitude":"-1.97685000","pk":26483,"image_id":"2006AU5916"},{"Name":"Tile","Location":"Islamic Middle East, room 42, case WW9","Latitude":"39.76586200","Longitude":"64.42234000","pk":30220,"image_id":"2006AY5617"},{"Name":"Sculpture","Location":"Sculpture, room 22, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":36026,"image_id":"2006AM7780"},{"Name":"Oil painting","Location":"Prints & Drawings Study Room, room 315, case 24, shelf R","Latitude":"52.88328900","Longitude":"-1.97685000","pk":6905,"image_id":"2006AU6480"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10895,"image_id":"2006AU8783"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10902,"image_id":"2006AU9234"}]
02-23 22:48:32.712 4239-4239/com.tamrefrank.www.listviewandroidstudio I/Process﹕ Sending signal. PID: 4239 SIG: 9
Code:
package com.tamrefrank.www.listviewandroidstudio;
//All the imports happen when you auto complete. Often you may have erros when you copy paste things directly because libraries may not get imported
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends ActionBarActivity {
private String [] drinks;
JSONArray jsonObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the content view to activity_main.xml
setContentView(R.layout.activity_main);
JSONArray object = new JSONArray();
object = getData();
Log.i("log_tag", jsonObject.toString());
// System.out.print("success: " + object.toString());
drinks = new String[3];
drinks[0] = "hi";
drinks[1] = "5";
drinks[2] = "3";
/**
* Lists require adapters-Adapters are the place that we store the various data items we want
to appear in the Lists. This will be handled in an adapter.
*/
ArrayAdapter<String> adapter;
//We will create the array adapter and reference it to our individual List item from the ListView and then to the array we just created- Drinks.
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,drinks);
//We finally will connect the adapter to the List View
ListView drinkLists = (ListView) findViewById(R.id.listView);
//Set the drinks array to the adapter below
drinkLists.setAdapter(adapter);
}
public JSONArray getData(){
new Thread(new Runnable() {
public void run() {
HttpGet httpGet = new HttpGet("https://stampwatch.herokuapp.com/");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
System.out.println(e);
}
try {
jsonObject = new JSONArray(stringBuilder.toString());
Log.i("log_tag", jsonObject.toString());
;
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("log_tag", jsonObject.toString());
}
}).start();
return jsonObject;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here:
Log.i("log_tag", jsonObject.toString());
NPE because jsonObject is null and trying to call toString() method for JSONObject using null object.
But why is the object null if I have made a request with that object?
Because jsonObject object is initialized inside getData(); method in which a Thread is used for getting data from api. means :
Log.i("log_tag", jsonObject.toString());
line executing just after starting Thread instead of wait until thread is finish.

I keep getting a nullpointer exception with my JSON Object Calls

For some reason I keep getting a nullpointer exception with my double parsing. AFter further inquiry there seems to be some issue with my JSON Objects but I have no clue what the issue is.I am pulling JSON data form openweathermap api. I scuessfully pulled and printed the data into the log.i, however when I try to access with the JSONObject I am getting an error. Please help.
Code:
package com.anuraagy.myweather;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import android.os.Build;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private JSONObject myObject,mainObject,nameObject;
private ImageView myImage;
private TextView titleText;
private String hello,weatherName,max_temp,min_temp;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
RequestTask task = new RequestTask();
task.execute(new String[]{"http://api.openweathermap.org/data/2.5/weather?q=Ashburn&APPID=970bf0e4978dae293b065f8f2830ba58"});
return rootView;
}
public class RequestTask extends AsyncTask<String, String, String> {
private TextView myView;
private String s;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
Log.i("", responseString);
return responseString;
}
#Override
protected void onPostExecute(String result){
Log.i("","hello");
super.onPostExecute(result);
try {
myObject = new JSONObject(result);
nameObject = myObject.getJSONObject("weather");
weatherName = nameObject.getString("main");
mainObject = myObject.getJSONObject("main");
Log.i("Wather Name",weatherName);
Log.i("mainObject",mainObject.toString());
hello = mainObject.getString("temp");
max_temp = mainObject.getString("temp_max");
min_temp = mainObject.getString("temp_min");
} catch(JSONException jsonException){
}
double f = Double.parseDouble(hello);
double max = Double.parseDouble(max_temp);
double min = Double.parseDouble(min_temp);
double realMax = (max - 273)* 1.8 + 32;
double realMin = (min - 273)* 1.8 + 32;
double realTemp = (max - 273)* 1.8 + 32;
int myMax = (int)realMax;
int myMin = (int)realMin;
int myWeather = (int)realTemp;
titleText = (TextView)getActivity().findViewById(R.id.textView3);
String fe = titleText.getText().toString();
fe.replace("definetly",weatherName);
myView = (TextView)getActivity().findViewById(R.id.textView);
// if()
// {
//
// }
// else
// {
//
// }
myImage = (ImageView)getActivity().findViewById(R.id.imageView);
myImage.setImageResource(R.drawable.clearnight);
String weather = myWeather + "";
myView.setText(weather + (char) 0x00B0 +"F");
// //Do anything with response..
}
}
}
}
Error:
10-16 10:01:26.398 664-664/com.anuraagy.myweather E/Trace﹕ error opening trace file: No such file or directory (2)
10-16 10:01:35.058 664-668/com.anuraagy.myweather D/dalvikvm﹕ GC_CONCURRENT freed 75K, 2% free 11112K/11335K, paused 17ms+3ms, total 312ms
10-16 10:01:35.058 664-664/com.anuraagy.myweather D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 282ms
10-16 10:01:35.498 664-664/com.anuraagy.myweather D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-16 10:01:38.388 664-680/com.anuraagy.myweather I/﹕ {"coord":{"lon":-77.49,"lat":39.04},"sys":{"type":1,"id":2856,"message":0.0194,"country":"US","sunrise":1413458470,"sunset":1413498574},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":721,"main":"Haze","description":"haze","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"base":"cmc stations","main":{"temp":288.03,"pressure":1008,"humidity":100,"temp_min":286.15,"temp_max":290.15},"wind":{"speed":2.86,"deg":261.502},"clouds":{"all":90},"dt":1413468071,"id":4744870,"name":"Ashburn","cod":200}
10-16 10:01:38.398 664-664/com.anuraagy.myweather I/﹕ hello
10-16 10:01:38.438 664-664/com.anuraagy.myweather D/AndroidRuntime﹕ Shutting down VM
10-16 10:01:38.438 664-664/com.anuraagy.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-16 10:01:38.448 664-664/com.anuraagy.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at java.lang.StringToReal.parseDouble(StringToReal.java:244)
at java.lang.Double.parseDouble(Double.java:295)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:141)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Be careful - "weather" is a JSONArray, not a JSONObject. The NullPointerException is likely due to that.
Try instead using myObject.getJSONArray("weather"), and from there iterate through the JSONObjects inside.
See here for more information on that last part: Accessing members of items in a JSONArray with Java
It looks like myObject doesn't have item named "temp", so:
- on line 133 you set hello to null
- on line 141 you pass that null to Double.parseDouble()
- get your exception because class Double can't digest null
That's it!
Check it in the debugger, but I'm almost sure - according to your stack trace

Android not sending mail

I am creating a application which gets the input from edit text and sends a mail acording to the information.I am using Http post to do this i want to communicate with the Php script to send the mail please have a look at my code..
Php script
<?php
$name = $_POST['name'];
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = "From: ".$name."\r\n";
$message .= $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
my Activity:
package dolphin.developers.com;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import dolphin.devlopers.com.R;
public class misc1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.eamilspoof);
EditText textw =(EditText) findViewById(R.id.editText1);
final String strd = textw.getText().toString();
EditText textw3 =(EditText) findViewById(R.id.editText2);
final String strd3 = textw3.getText().toString();
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
EditText textw3dd =(EditText) findViewById(R.id.editText3);
final String name = textw3d.getText().toString();
EditText textw3df =(EditText) findViewById(R.id.editText4);
final String subject = textw3d.getText().toString();
Button pds = (Button)findViewById(R.id.button1d);
pds.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String site = "www.dolphin123.net78.net/mailer.php";
String namer1 = name;
String to = strd;
String from = strd3;
String subject1 = subject;
String message = strd3d;
String content = "";
try
{
/* Sends data through a HTTP POST request */
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(site);
List <NameValuePair> params = new ArrayList <NameValuePair> ();
params.add(new BasicNameValuePair("name", namer1));
params.add(new BasicNameValuePair("to", to));
params.add(new BasicNameValuePair("from", from));
params.add(new BasicNameValuePair("subject", subject1));
params.add(new BasicNameValuePair("message", message));
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* Reads the server response */
HttpResponse response = httpClient.execute(httpPost);
InputStream in = response.getEntity().getContent();
StringBuffer sb = new StringBuffer();
int chr;
while ((chr = in.read()) != -1)
{
sb.append((char) chr);
}
content = sb.toString();
in.close();
/* If there is a response, display it */
if (!content.equals(""))
{
Log.i("HTTP Response", content);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
};
}
}
Logcat :
08-10 17:55:20.405: W/System.err(12988): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=www.dolphin123.net78.net/mailer.php
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
08-10 17:55:20.410: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-10 17:55:20.410: W/System.err(12988): at dolphin.developers.com.misc1$1.onClick(misc1.java:87)
08-10 17:55:20.410: W/System.err(12988): at android.view.View.performClick(View.java:4211)
08-10 17:55:20.410: W/System.err(12988): at android.view.View$PerformClick.run(View.java:17267)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.handleCallback(Handler.java:615)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.dispatchMessage(Handler.java:92)
new Log:
08-05 13:08:17.365: D/SntpClient(73): request time failed: java.net.SocketException: Address family not supported by protocol
Prepend the protocol to the String representation of your URI.
So it should be: "http://www.dolphin123.net78.net/mailer.php"
You can your url with above url with prepend http://

Trying to access database in tab widget

I'm sure I have just structured my code wrong or something but I have been looking at it soo long I can see it.
I have managed to get a class working to access my database and bring back data, but when I try to build this class into my tab widget it doesn't seem to work.
This is were I call the class:
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, recipelist.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("recipe").setIndicator("recipe", res.getDrawable(R.drawable.ic_tab_list)).setContent(intent);
tabHost.addTab(spec);
and this is the class with the database code:
package fridge.mate;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class recipelist extends Activity {
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText("gfgfgf...");
}
public static final String KEY_121 = "http://www.bankruptcy.co.uk/1.php"; //i use my real ip here
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","beans"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", name: "+json_data.getString("name")+
", servings: "+json_data.getString("servings")+
", discription: "+json_data.getString("discription")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
txt.setText("Connecting...");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
Few notes:
You are calling setContentView() twice. One is enough. So which one is the right one?
You are calling new LinearLayout(getApplicationContext()). Activity is a Context, so you can call new LinearLayout(this). Same for TextView.
I don't see any Tabs. Where are they? I only see LinearLayout and TextView inside it.
You should not perform long-running task in UI thread (EDT). Use AsyncTask for this.
Take a look at Tabs example to see how they did it.

Categories