Line -> JSONArray jArray=new JSONArray(result); giving nullpointer exception - java

package com.example.fyptrialapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
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.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class SearchByName extends Activity{
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream=null;
Intent i;
//public static final String recipes[]=new String[]{"Almond-Sheera","Bhel","Bread-Pizzas","Carrot-Pickle","Carrot-Relish"};
String recipes[];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_recipe);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button b2=(Button)findViewById(R.id.bSearchByName);
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/fypTrial2/searchByName.php");
response = httpclient.execute(httppost); // Execute HTTP Post Request
inputStream = response.getEntity().getContent();
String result=null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line=null;
while((line=reader.readLine())!= null){
sb.append(line+"\n");
}
inputStream.close();
result=sb.toString();
JSONArray jArray=new JSONArray(result);// this statment gives error
for(int i=0;i<jArray.length();i++){
JSONObject json=jArray.getJSONObject(i);
recipes[i]=json.getString("name");
}
}
catch(Exception e){
Log.e("log_tag3", "Error convering result"+e.toString());
}
ArrayAdapter<String> ac=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,recipes);
AutoCompleteTextView tv=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
tv.setAdapter(ac);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent("com.example.practice.Search_Result");
startActivity(i);
}
});
}
}
ERROR
java.nullpointerexception. Error converting result variable.And the
fatal main error
If i want to use ASnk task how should i write it.

JSON syntax never starts as an array. It could be that it starts with { followed by [, but never straight to [. This is why trying to convert your results to JSONArray will not work. You should therefor try to get the object first, then the array elements.
JSONObject jo = new JSONObject(result);
JSONArray jArray = jo.getJSONArray("keyIdentifyer");
If you dont have the array key identifyer, you could try to iterate or get the first element. See this post answear on iterations when no keys are present.

You should indeed use AsyncTask for the networking part. Your app probably already crashes with a NetworkOnMainThread error follow this link for the usasge of AsyncTask.
But that besides, you are providing to little code to point to a reason for the NullPointerException. You should always check if an object is not null if it may occur it is.
try{
//your code
}catch(NullPointerException ex){
ex.printStackTrace();
}

Related

New to okhttp3, no idea why it won't show the results on TextView

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.OkHttpClient;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView textView = findViewById(R.id.text_view_id);
final String IMAGE1 = "storage/emulated/0/Download/image_1.jpeg";
File file1 = new File(IMAGE1);
try {
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("images", "image_1.jpeg",
RequestBody.create(file1, MEDIA_TYPE_JPEG))
.addFormDataPart("organs", "flower")
.build();
Request request = new Request.Builder()
.url("https://my-api.plantnet.org/v2/identify/all?api-key=123")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
textView.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I understand that I'm trying to run a network activity here on the main thread. That's why I included the StrictMode permitAll thing to get around the issue (I saw an answer to a similar topic that suggested doing so). I am trying to use the PlantNet API here and I use my phone for testing. The same phone where the image is saved.
go see retrofit
it provides a nice and easy way to make your network calls off the main thread

Android internet access throws IOException

I am trying to write an app that pings a web page, which will then trigger an action.
package com.anton.lightcontrol;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Switch onOffSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onOffSwitch = (Switch) findViewById(R.id.onOffSwitch);
onOffSwitch.setChecked(true);
onOffSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onOffSwitch.isChecked()==true) {
onOffSwitch.setTextColor(Color.GREEN);
LightConnection("http://raspberrypi/toggle_on.py");
}
else if (onOffSwitch.isChecked()==false){
onOffSwitch.setTextColor(Color.RED);
LightConnection("http://raspberrypi/toggle_off.py");
}
}
});
}
private void LightConnection(final String accessUrl){
(new Thread(new Runnable() {
#Override
public void run() {
try{
Log.d("EXEC", "#1");
URL url = new URL(accessUrl);
Log.d("EXEC", "#2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Log.d("EXEC", "#3");
InputStreamReader input = new InputStreamReader(conn.getInputStream(), "utf-8");
Log.d("EXEC", "#4");
BufferedReader reader = new BufferedReader(input,2000);
Log.d("EXEC", "#5");
String line = reader.readLine();
Log.d("EXEC", "#6");
}
catch (IOException e){
Log.d("EXEC", "#10 - CATCH");
onOffSwitch.setTextColor(Color.YELLOW);
}
}
})).start();
}
}
My debug output looks like the following:
D/EXEC: #1
D/EXEC: #2
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/EXEC: #3
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/EXEC: #10 - CATCH
I have been searching for a solution for the isSBSettingEnabled false error, but I couldn't find anything that helped me.
I am running my app on a Samsung M20 smartphone.
This technically isn't an error, since it's alerting you that you're not using a network security config. More information on this here: Network security configuration: Android Developer Docs.
However, if you're limited to using HTTP, you can resolve connection issues by permitting cleartext traffic by adding this to your <application> tag in AndroidManifext.xml:
android:usesCleartextTraffic="true"

Can't getApplicationContext. because java.lang.NullPointerException

I want make mechanism that I can call from any place in app to write in file.
I make next class:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import android.content.Context;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.content.Context;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class LogFile extends Activity {
public void writeFile(String msg)
{
Log.d("writeFile", "writeToFile");
try {
Context context = getApplicationContext();
FileOutputStream fos = context.openFileOutput("log.txt", Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter outputStream = new BufferedWriter(osw);
outputStream.write(msg);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("writeFile", "File not found");
} catch (NullPointerException e) {
e.printStackTrace();
Log.d("writeFile", "NullPointerException");
} catch (IOException e) {
e.printStackTrace();
Log.d("writeFile", "File problems");
}
}
}
But in this line
Context context = getApplicationContext();
I have error
W/System.err: java.lang.NullPointerException
W/System.err: at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:185)
W/System.err: at com.example.tracklogger.LogFile.writeFile(LogFile.java:37)
I'm not sure this is the "right" way to solve your problem or make it work.
I think the problem is that you are passing the value of Activity's context (and this is null, for that reason it throws that Exception) and you need Application's context.
In my personal case, I solved a similar problem as follows:
GlobalVars.java file, containing all "global variables", like Applications context (not Activity's context):
public class GlobalVars extends Application {
public static Context context;
#Override public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
Taken from here: Getting the Application Context
Good luck, and happy coding!

Get XML file from url to Android Application

I have a problem to get .xml data from website and parse to android application, i have try many suggestion but never work. It works fine when i open file in assets folder, but when i try to get from url, it show nothing
This is my Activity Class
package com.android.baliweather;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
public class Prakiraan extends Activity {
/** Called when the activity is first created. */
private ListView listView;
private TextView judul;
private String URL_MAIN = "http://localhost/android/propinsi_17_1.xml";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prakiraan_cuaca);
judul = (TextView) findViewById(R.id.menu1);
listView = (ListView) findViewById(R.id.listview);
bindDataToListing();
}
private void bindDataToListing() {
try {
URL url = new URL("http://localhost/android/propinsi_17_1.xml");
URLConnection connection = url.openConnection();
//URLConnection connection = url.openConnection();
//HttpURLConnection httpConnection = (HttpURLConnection)connection;
//InputStream in = httpConnection.getInputStream();
SAXParserFactory saxparser = SAXParserFactory.newInstance();
SAXParser parser = saxparser.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
XMLParser pc = new XMLParser();
xmlReader.setContentHandler(pc);
//InputStream is = getAssets().open("propinsi_17_1.xml");
//InputStream is = new URL(URL_MAIN).openStream();
xmlReader.parse(new InputSource(connection.getInputStream()));
BindingData bindingData = new BindingData(this, pc.kota, pc.cuaca, pc.suhuMin, pc.suhuMax, pc.kelembapanMin, pc.kelembapanMax, pc.kecepatanAngin, pc.arahAngin);
listView.setAdapter(bindingData);
}
catch (Exception e) {
e.getMessage();
}
}
}
I think the problem only on this class, but i have no idea which one. Please help
It might be android.os.NetworkOnMainThreadException - you're trying to do time-heavy task in a UI thread and the system is preventing you from doing it (you can possibly see this in your logcat). You can implement AsyncTask in order to do it in the background thread.
It may also be that you forgot to add the permission in a manifest file - <uses-permission android:name="android.permission.INTERNET" />

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