java.lang.Nullpointerexception using JSONParser - java

I am using MySQL database, and I'm selecting my data from database using JSONParser.class I found on the internet, but the value always showing Null, please help, i'm new at this
Here's my main activity class:
public class Profil extends Activity{
private static String url = "http://10.0.2.2/koperasidb/tampil_profil.php";
private static final String TAG_ANGGOTA = "anggota";
private JSONParser jsonParser;
private JSONObject json;
private JSONArray jArray;
String kodeanggota;
private Session session;//global variable
private String no_ba,nm,jk,agama,tmptlahir,tgllahir,blnlahir,thnlahir,status,alamat,notelp,email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new Session(this); //onCreate Session class
//mengambil string kdanggota
kodeanggota = session.getkdanggota();
jsonParser = new JSONParser();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("kode", kodeanggota));
//profil = new ArrayList<HashMap<String, String>>();
try {
json = jsonParser.makeHttpRequest(url, "POST", postParameters);
jArray = json.getJSONArray(TAG_ANGGOTA);
for (int i = 0; i < jArray.length(); i++) {
JSONObject job = jArray.getJSONObject(i);
no_ba = job.getString("no_ba");
nm = job.getString("nama");
jk = job.getString("jk");
agama = job.getString("agama");
tmptlahir = job.getString("tmptlhr");
tgllahir = job.getString("tgllhr");
blnlahir = job.getString("blnlhr");
thnlahir = job.getString("thnlhr");
status = job.getString("status");
alamat = job.getString("alamat");
notelp = job.getString("notelp");
email = job.getString("email");
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
tampilkanprofil();
}
}
private void tampilkanprofil() {
TextView profilnama = (TextView) findViewById(R.id.profilnamaanggota);
profilnama.setText(nm);
TextView profiljk = (TextView) findViewById(R.id.profiljk);
profiljk.setText(jk);
TextView profilnoba = (TextView) findViewById(R.id.profilkodeba);
profilnoba.setText(no_ba);
TextView profilagama = (TextView) findViewById(R.id.profilagama);
profilagama.setText(agama);
TextView profilttl = (TextView) findViewById(R.id.profilttl);
profilttl.setText(tmptlahir + ", " + tgllahir + " " + blnlahir + " " + thnlahir);
TextView profilstatus = (TextView) findViewById(R.id.profilstatus);
profilstatus.setText(status);
TextView profilalamat = (TextView) findViewById(R.id.profilalamat);
profilalamat.setText(alamat);
TextView profilnotelp = (TextView) findViewById(R.id.profilnotelp);
profilnotelp.setText(notelp);
TextView profilemail = (TextView) findViewById(R.id.profilemail);
profilemail.setText(email);
}
}
And here's my php file:
<?php
include ("koneksi.php");
$response = array();
$kd=$_POST['kdanggota'];
$result = mysql_query("SELECT * FROM anggota_baru WHERE kd_anggota ='$kd' ") or die(mysql_error());
$response["anggota"] = array();
while($row = mysql_fetch_array($result)){
$profil = array();
$profil["no_ba"] = $row["no_ba"];
$profil["nama"] = $row["nama_lengkap"];
$profil["jk"] = $row["kelamin"];
$profil["agama"] = $row["agama"];
$profil["tmptlhr"] = $row["tempat_lahir"];
$profil["ttgllhr"] = $row["tgl_lahir"];
$profil["blnlhr"] = $row["bln_lahir"];
$profil["thnlhr"] = $row["thn_lahir"];
$profil["status"] = $row["status_nikah"];
$profil["alamat"] = $row["alamat"];
$profil["notelp"] = $row["no_telp"];
$profil["email"] = $row["email"];
array_push($response["anggota"],$profil);
}
echo json_encode($response);
?>
here's my logcat error:
05-08 20:20:26.246: WARN/System.err(871): org.json.JSONException: No value for no_ba
05-08 20:20:26.256: WARN/System.err(871): at org.json.JSONObject.get(JSONObject.java:354)
05-08 20:20:26.256: WARN/System.err(871): at org.json.JSONObject.getString(JSONObject.java:510)
05-08 20:20:26.256: WARN/System.err(871): at com.randy.koperasidb.Profil.onCreate(Profil.java:55)
05-08 20:20:26.256: WARN/System.err(871): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-08 20:20:26.266: WARN/System.err(871): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
05-08 20:20:26.266: WARN/System.err(871): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
05-08 20:20:26.266: WARN/System.err(871): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-08 20:20:26.286: WARN/System.err(871): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
05-08 20:20:26.286: WARN/System.err(871): at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 20:20:26.296: WARN/System.err(871): at android.os.Looper.loop(Looper.java:123)
05-08 20:20:26.296: WARN/System.err(871): at android.app.ActivityThread.main(ActivityThread.java:3647)
05-08 20:20:26.306: WARN/System.err(871): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 20:20:26.306: WARN/System.err(871): at java.lang.reflect.Method.invoke(Method.java:507)
05-08 20:20:26.316: WARN/System.err(871): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-08 20:20:26.316: WARN/System.err(871): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-08 20:20:26.327: WARN/System.err(871): at dalvik.system.NativeStart.main(Native Method)
05-08 20:20:26.346: DEBUG/AndroidRuntime(871): Shutting down VM
05-08 20:20:26.346: WARN/dalvikvm(871): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): FATAL EXCEPTION: main
05-08 20:20:26.366: ERROR/AndroidRuntime(871): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.randy.koperasidb/com.randy.koperasidb.Profil}: java.lang.NullPointerException
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.os.Looper.loop(Looper.java:123)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.app.ActivityThread.main(ActivityThread.java:3647)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at java.lang.reflect.Method.invoke(Method.java:507)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at dalvik.system.NativeStart.main(Native Method)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): Caused by: java.lang.NullPointerException
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at com.randy.koperasidb.Profil.tampilkanprofil(Profil.java:78)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at com.randy.koperasidb.Profil.onCreate(Profil.java:72)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
05-08 20:20:26.366: ERROR/AndroidRuntime(871): ... 11 more
05-08 20:20:26.396: WARN/ActivityManager(61): Force finishing activity com.randy.koperasidb/.Profil
05-08 20:20:26.416: WARN/ActivityManager(61): Force finishing activity com.randy.koperasidb/.Home
05-08 20:20:26.927: WARN/ActivityManager(61): Activity pause timeout for HistoryRecord{40693400 com.randy.koperasidb/.Profil}
05-08 20:20:28.177: INFO/Process(871): Sending signal. PID: 871 SIG: 9
05-08 20:20:28.207: INFO/ActivityManager(61): Process com.randy.koperasidb (pid 871) has died.
05-08 20:20:28.217: INFO/WindowManager(61): WIN DEATH: Window{406a6770 com.randy.koperasidb/com.randy.koperasidb.login paused=false}
05-08 20:20:28.257: ERROR/InputDispatcher(61): channel '40774e40 com.randy.koperasidb/com.randy.koperasidb.Home (server)' ~ Consumer closed input channel or an error occurred. events=0x8
05-08 20:20:28.257: ERROR/InputDispatcher(61): channel '40774e40 com.randy.koperasidb/com.randy.koperasidb.Home (server)' ~ Channel is unrecoverably broken and will be disposed!
05-08 20:20:28.327: INFO/WindowManager(61): WIN DEATH: Window{40774e40 com.randy.koperasidb/com.randy.koperasidb.Home paused=true}
05-08 20:20:29.027: WARN/InputManagerService(61): Got RemoteException sending setActive(false) notification to pid 871 uid 10041

You are passing parameter from client app with name "kode" in line
postParameters.add(new BasicNameValuePair("kode", kodeanggota));
But you are accepting with name "kdanggota" in line
$kd=$_POST['kdanggota'];
Therefore server is sending empty array and you are not checking either array is empty or not. Please use same name of parameter while sending and receiving data.

one error I can see without the logcat which is as following;
1 - You have assigned key kode in your BasicNameValuePair while you are trying to fetch 'kdanggota' in you php wile in $_POST which does not exists. So change the fourth line of php as following
`$kd=$_POST['kode'];` //You need to write kode here because that is what is the key for your pair.
Please also post logcat for more information

Related

App has stopped working Android Jsonparser

I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil 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:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
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:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasda‌​sdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}

Android: How to have a common socket connection to server in all activities

I am pretty new to android. How could I make a socket connection to a server which is available to all the activities, instead of me establishing connection to the same server in every activity?
In the MainActivity I have a thread which is running, but this is thread is not accesible by other activities.
public class MainActivity extends Activity implements OnItemSelectedListener {
private Socket socket;
private static final int SERVERPORT = 8020;
private static final String SERVER_IP = "192.168.1.36";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ServerThread()).start();
}
class ClientThread implements Runnable {
private Socket socket;
private static final int SERVERPORT = 8020;
private static final String SERVER_IP = "192.168.1.36";
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
How do i make the same connection to server on 192.168.1.36 available to all activities instead of me creating a connection on every activity.
EDIT TO ANSWER
I created a class which stores all the connection parameters
package com.example.clientmobile2;
public class DataHolderClass {
private static DataHolderClass dataObject = null;
private DataHolderClass() {
// left blank intentionally
}
public static DataHolderClass getInstance() {
if (dataObject == null)
dataObject = new DataHolderClass();
return dataObject;
}
private int server_port=8020;
private String server_ip="192.168.1.33";;
public int get_server_port() {
return server_port;
}
public String get_server_ip() {
return server_ip;
}
}
MainActivity is as follows :-
public class MainActivity extends Activity implements OnItemSelectedListener {
private static final int SERVERPORT = DataHolderClass.getInstance().get_server_port();
private static final String SERVER_IP = DataHolderClass.getInstance().get_server_ip();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickon(View view) {
Socket socket = null;
try{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//sending the message to the linino as 0 to turn of the light
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println("0");
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The application crashes everytime i click on the button associated with onClickOn.
Error Log
05-08 10:38:40.171: E/AndroidRuntime(12909): FATAL EXCEPTION: main
05-08 10:38:40.171: E/AndroidRuntime(12909): Process: com.example.clientmobile2, PID: 12909
05-08 10:38:40.171: E/AndroidRuntime(12909): java.lang.IllegalStateException: Could not execute method of the activity
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.view.View$1.onClick(View.java:3841)
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.view.View.performClick(View.java:4456)
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.view.View$PerformClick.run(View.java:18462)
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.os.Handler.handleCallback(Handler.java:733)
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.os.Handler.dispatchMessage(Handler.java:95)
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.os.Looper.loop(Looper.java:136)
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.app.ActivityThread.main(ActivityThread.java:5102)
05-08 10:38:40.171: E/AndroidRuntime(12909): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909): at java.lang.reflect.Method.invoke(Method.java:515)
05-08 10:38:40.171: E/AndroidRuntime(12909): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-08 10:38:40.171: E/AndroidRuntime(12909): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-08 10:38:40.171: E/AndroidRuntime(12909): at dalvik.system.NativeStart.main(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909): Caused by: java.lang.reflect.InvocationTargetException
05-08 10:38:40.171: E/AndroidRuntime(12909): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909): at java.lang.reflect.Method.invoke(Method.java:515)
05-08 10:38:40.171: E/AndroidRuntime(12909): at android.view.View$1.onClick(View.java:3836)
05-08 10:38:40.171: E/AndroidRuntime(12909): ... 11 more
05-08 10:38:40.171: E/AndroidRuntime(12909): Caused by: java.lang.NullPointerException
05-08 10:38:40.171: E/AndroidRuntime(12909): at com.example.clientmobile2.MainActivity.onClickon(MainActivity.java:331)
you can create a singleton class and define that object there or either use application class which is provided by android and then define your socket object there.Then your object will accessible in all activities. read here how to use Application class.
here in this case you have to use SINGLETON CLASS.from your first screen you have to set the creditiontials then you have yo get them at any screen.you can use the below code:
public class DataHolderClass {
private static DataHolderClass dataObject = null;
private DataHolderClass() {
// left blank intentionally
}
public static DataHolderClass getInstance() {
if (dataObject == null)
dataObject = new DataHolderClass();
return dataObject;
}
private int server_port;
private String server_ip;
public String get_server_port() {
return server_port;
}
public void set_server_port(String server_port) {
this._server_port = server_port;
}
public String get_server_ip() {
return server_ip;
}
public void set_server_ip(String server_ip) {
this.server_ip= server_ip;
}
}
now in your activity you have to set the values like below:
DataHolderClass.getInstance().set_server_port("8020");
DataHolderClass.getInstance().set_server_ip("192.168.1.36");
now to get the values use below code:
String a = DataHolderClass.getInstance().get_server_port();
String b = DataHolderClass.getInstance().get_server_ip();

Android get data from MySql table

I am developing an android app... where I developed a table in MySql and table has certain results for values of 1-10 and all the values are entered seperately ...
in my android application when a particular value is displayed the result of that value has to be taken from the table... but it is not working correctly ...the message is getting like 'unfortunately application closed'... i am adding my code here... please check the code and if found any mistake pls help.....
Activity.java
public class FirstResult extends Activity
{
String pid;
TextView txtName;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://iascpl.com/app/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
//private static final String TAG_PID = "pid";
//private static final String TAG_NUMBER = "number";
//private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.firstresult_xm);
TextView txt1 = (TextView) findViewById (R.id.textView2);
txt1.setText(getIntent().getStringExtra("name10"));
pid = txt1.getText().toString();
new GetProductDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FirstResult.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.textView3);
// display product data in EditText
txtName.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
php file
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM prediction WHERE pid = $pid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["number"] = $result["number"];
// $product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
my Logcat
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Looper.loop(Looper.java:137)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:44:12.701: E/AndroidRuntime(7643): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:44:12.701: E/AndroidRuntime(7643): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:44:12.701: E/AndroidRuntime(7643): at dalvik.system.NativeStart.main(Native Method)
11-05 11:52:08.052: E/Trace(7805): error opening trace file: No such file or directory (2)
11-05 11:56:14.171: E/AndroidRuntime(7805): FATAL EXCEPTION: main
11-05 11:56:14.171: E/AndroidRuntime(7805): android.os.NetworkOnMainThreadException
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Looper.loop(Looper.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:56:14.171: E/AndroidRuntime(7805): at dalvik.system.NativeStart.main(Native Method)
11-05 11:56:25.961: E/Trace(7893): error opening trace file: No such file or directory (2)
runOnUiThread(new Runnable() {
#Override
public void run()
{
// TODO Auto-generated method stub
try {
txt3.setText(product.getString(TAG_DESCRIPTION));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}else{
// product with pid not found
}
add this line after
/ get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.textView3);
that will solve the issue
You need to post the stack trace of the problem. You will find it in your logcat view. Also, on a sidenote:
runOnUiThread(new Runnable() {
public void run() {
This doesnt make any sense at all at this place because you are basically running a background thread, then you synchronize it and run it on the main thread. Depending on your settings, that won't work because Android does not allow network operations on the main / UI thread.
Edit after LogCat was added:
It's exactly what I mentioned. Android does not allow you to run network traffic on the UI thread. Remove that runOnUiThread stuff from the runOnBackground.
Now to set the data you can two one of two things:
Add the runOnUiThread part where you set the textView. Something like:
runOnUiThread(new Runnable() {
public void run() {
TextView tv = findViewById...
tv.setText(...
}
}
Return the object you need. This is actually how AsyncTask is supposed to work:
In your AsyncTask's runOnBackground, you'd do:
return product.getString(TAG_DESCRIPTION)
Then, in onPostExecute you get that String and set it to your TextViews.

try catch - Unable to instantiate activity ComponentInfo

I have two methods to update and delete data in my app, I have implemeted try catches within my switch statement and am now getting the following error:
01-14 20:38:58.778: D/AndroidRuntime(273): Shutting down VM
01-14 20:38:58.778: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-14 20:38:58.798: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-14 20:38:58.798: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.flybase2/com.example.flybase2.viewEdit}: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-14 20:38:58.798: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at com.example.flybase2.viewEdit.<init>(viewEdit.java:63)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstanceImpl(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstance(Class.java:1429)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-14 20:38:58.798: E/AndroidRuntime(273): ... 11 more
Can anyone see the issue? It works perfectly without the try catches.
Heres the class:
package com.example.flybase2;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class viewEdit extends Activity implements OnClickListener{
EditText namePassedEdit;
EditText numPassedEdit;
EditText emailPassedEdit;
EditText commentPassedEdit;
Button bUpdate;
Button bDelete;
long passedID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editview);
DBHandler displayEdit = new DBHandler(this, null, null);
Bundle extras = getIntent().getExtras();
if (extras != null) {
passedID = extras.getLong("passedID");
}
displayEdit.open();
String returnedNameToEdit = displayEdit.getName(passedID);
String returnedNumToEdit = displayEdit.getNum(passedID);
String returnedEmailToEdit = displayEdit.getEmail(passedID);
String returnedCommentToEdit = displayEdit.getComments(passedID);
namePassedEdit = (EditText) findViewById(R.id.inputNameEdit);
numPassedEdit = (EditText) findViewById(R.id.inputTelNoEdit);
emailPassedEdit = (EditText) findViewById(R.id.inputEmailEdit);
commentPassedEdit = (EditText) findViewById(R.id.inputCommentEdit);
bUpdate = (Button) findViewById (R.id.btnAddConEdit);
bDelete = (Button) findViewById (R.id.btnDeleteContact);
namePassedEdit.setText(returnedNameToEdit);
numPassedEdit.setText(returnedNumToEdit);
emailPassedEdit.setText(returnedEmailToEdit);
commentPassedEdit.setText(returnedCommentToEdit);
bUpdate.setOnClickListener(this);
bDelete.setOnClickListener(this);
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
#Override
public void onClick(View updateOrDeleteClicked) {
boolean check = true;
switch(updateOrDeleteClicked.getId()){
case (R.id.btnAddConEdit):
try
{
DBHandler updateData = new DBHandler(this, null, null);
updateData.open();
updateData.updateData(passedID, nameEdit, telEdit, emailEdit, commentEdit);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
case (R.id.btnDeleteContact):
try
{
DBHandler deleteContact = new DBHandler(this, null, null);
deleteContact.open();
deleteContact.deleteData(passedID);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
}
}
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
These lines aren't inside a method, and you can't use them like that. You're getting a null pointer on namePassedEdit because it's trying to initialize them when the class is created, and they aren't assigned anything yet.
One issue I see here is:
if(check = true); //This ends if statement here and here you are assigning true to check nothing more than that..
I guess what you need here is:
if(check){....}
The main problem I can find is that you close the braces for your onCreate on line 59. Leaving the following lines between functions.
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
If you move these up into the onCreate it will probably fix your issue. Also as #Nambari said in their answer, in your if statements you are checking if check was set to true. You need to change this to:
if(check)

Android resource not found exception

My application code is as follows,
public class Alarm extends MainActivity {
public String str;
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB " + msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
str += " :";
str += "\n";
}
}
}
EditText user_value;
Button startalarm;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
startalarm = (Button) findViewById(R.id.startalarm);
user_value = (EditText) findViewById(R.id.user_value);
startalarm.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(user_value.length()==0)
{
Toast.makeText(getBaseContext(), "Please enter a value.", Toast.LENGTH_LONG).show();
}
SQLiteDatabase aa = openOrCreateDatabase("MLIdata", MODE_WORLD_READABLE, null);
Cursor c = aa.rawQuery("SELECT CblocationName FROM MLITable WHERE CblocationCode = '"+str+"'", null);
c.moveToFirst();
c.getString(c.getColumnIndex("CblocationName"));
String sas = user_value.getText().toString();
if(sas==getString(c.getColumnIndex("CblocationName")))
{
//here comes the alarm code
Toast.makeText(getBaseContext(), "till here it has executed.", Toast.LENGTH_LONG).show();
Notification notification = new Notification(android.R.drawable.ic_popup_reminder,
"My Notification", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
}
});
}
}
Though there are no errors, when I run this code it force closes when I press the 'startalarm' button.
My log cat is as follows,
11-05 01:31:03.029: W/ResourceType(1554): No package identifier when getting value for resource number 0x00000000
11-05 01:31:03.029: W/dalvikvm(1554): threadid=1: thread exiting with uncaught exception (group=0x40018578)
11-05 01:31:03.029: E/AndroidRuntime(1554): FATAL EXCEPTION: main
11-05 01:31:03.029: E/AndroidRuntime(1554): android.content.res.Resources$NotFoundException: String resource ID #0x0
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.content.res.Resources.getText(Resources.java:201)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.content.res.Resources.getString(Resources.java:254)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.content.Context.getString(Context.java:183)
11-05 01:31:03.029: E/AndroidRuntime(1554): at my.project.mil.Alarm$1.onClick(Alarm.java:68)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.view.View.performClick(View.java:2485)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.view.View$PerformClick.run(View.java:9080)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.os.Handler.handleCallback(Handler.java:587)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.os.Looper.loop(Looper.java:130)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-05 01:31:03.029: E/AndroidRuntime(1554): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 01:31:03.029: E/AndroidRuntime(1554): at java.lang.reflect.Method.invoke(Method.java:507)
11-05 01:31:03.029: E/AndroidRuntime(1554): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-05 01:31:03.029: E/AndroidRuntime(1554): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-05 01:31:03.029: E/AndroidRuntime(1554): at dalvik.system.NativeStart.main(Native Method)
I've tried all the solutions given in the below link, yet none helped.
Android, string resource not found
Help required,
Thank you.
I had no idea my comment would fix your exception. I will put it as an answer so you can close this question.
Change this line:
if(sas==getString(c.getColumnIndex("CblocationName")))
to
if(sas.equals(getString(c.getColumnIndex("CblocationName"))))
Read up on String comparison if you don't understand why this should be like this.

Categories