From json file to String[] - java

I am not able to find the error android app is forcefully stopped. When I use the general sample data which is commented in this program it works fine but when i use this code it gets crashed.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] country;
String[] population;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("maindata");
rank = new String[m_jArry.length()];
country = new String[m_jArry.length()];
population = new String[m_jArry.length()];
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
rank[i] = jo_inside.getString("rank");
country[i] = jo_inside.getString("country");
population[i] = jo_inside.getString("population");
System.out.println(rank[i]);
}
}catch (JSONException e){
e.printStackTrace();
}
// Generate sample data
/*rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
country = new String[] { "China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
"Russia", "Japan" };
population = new String[] { "1,354,040,000", "1,210,193,422",
"315,761,000", "237,641,326", "193,946,886", "182,912,000",
"170,901,000", "152,518,015", "143,369,806", "127,360,000" };*/
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
WorldPopulation wp = new WorldPopulation(rank[i], country[i],
population[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
Json file contains :
{
"maindata": [
{
"country": "rumbo",
"rank": "45",
"population": "45000"
},
{
"country": "reck",
"rank": "46",
"population": "4500"
}
]
}
01-13 06:22:27.024 2057-2057/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-13 06:22:27.024 2057-2057/? E/android.os.Debug: failed to load memtrack module: -2
01-13 06:22:27.045 2057-2070/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-13 06:22:27.406 2073-2073/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-13 06:22:27.406 2073-2073/? E/android.os.Debug: failed to load memtrack module: -2
01-13 06:22:27.707 2086-2086/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robosoft.elections, PID: 2086
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.robosoft.elections/com.robosoft.elections.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' 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 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.robosoft.elections.MainActivity.onCreate(MainActivity.java:55)
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) 
01-13 06:22:27.754 735-735/? E/EGL_emulation: tid 735: eglCreateSyncKHR(1181): error 0x3004 (EGL_BAD_ATTRIBUTE)

You need to create asset folder on right location in you project directory.
For that follow following direction:
1. switch to Project Files from dropdown on top of project tab.
2. Navigate to app > src/main.
3. Create asset directory in src/main directory and copy data.json file.
And you are good to go.

Related

Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList in android studio

I am trying to permanently save some of the visited places by the user. So, when ever i run my project in android studio i get the error
"Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList"
Here is my code:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static ArrayList<String> places= new ArrayList<>();
static ArrayList<LatLng> locations = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.lucifer.memorableplaces", Context.MODE_PRIVATE);
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
places.clear();
latitudes.clear();
longitudes.clear();
locations.clear();
try {
places = (ArrayList<String>)ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList<String>())));
latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("latitudes", ObjectSerializer.serialize(new ArrayList<String>())));
longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("longitudes", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
if (places.size() > 0 && latitudes.size() > 0 && longitudes.size() > 0) {
if (places.size() == latitudes.size() && latitudes.size() == longitudes.size()) {
for (int i = 0; i < latitudes.size(); i++) {
locations.add(new LatLng(Double.parseDouble(latitudes.get(i)), Double.parseDouble(longitudes.get(i))));
}
}
} else {
places.add("Add a new place...");
locations.add(new LatLng(0, 0));
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, places);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra("placeNumber", i);
startActivity(intent);
}
});
}
}
and i get the following error:
Process: com.example.lucifer.memorableplaces, PID: 15910
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lucifer.memorableplaces/com.example.lucifer.memorableplaces.MainActivity}: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList
at com.example.lucifer.memorableplaces.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:5301)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2291)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378) 
at android.app.ActivityThread.access$800(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5433) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 
at dalvik.system.NativeStart.main(Native Method) 
The error is at
places = (ArrayList)ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList())));
I finally got the answer, the error was caused because i was casting a class to arrayList. so i just changed my class to arrayList first then i casted it back to arrayList which solved my problem.
This way. Here i coded MainActivity.class
sharedPreferences.edit().putString("places",ObjectSerializer.serialize(MainActivity.class)).apply();
Whereas it has to be MainActivity.places in following Way
sharedPreferences.edit().putString("places",ObjectSerializer.serialize(MainActivity.places)).apply();
So, here i was actually casting a class to arrayList which gave me this error. Hope any beginner will prevent this mistake from this Question.
Thanks You All...

Android Java Adapter, PHP JSON

Can someone give me a example of a right json file and php, so I can use it in the Android GET method? I think my files are wrong. This are the newest files regarding JSON and PHP
data.json
{
"Heroes":
[
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
},
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
},
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
},
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
}
]
}
data.php
<?php
$jsonData = file_get_contents("data.json");
$json = json_encode($jsonData,true);
header('Content-Type: application/json');
echo $json;
?>
I am new to Android App's coding.
May you can help me out, with a stupid problem.
I've tried to make an app from a youtube tutorial,
there it workes fine but I got several problems now I really need to fix.
The app is basicly an App that shows me a RecyclerViewCard with an Image, HeaderText and About text, the content is in a php file on my localhost.
<?php
$json2 = array(
"error" => "false",
"Heroes" => array(
'name' => 'Spiderman',
'about' => 'Spiderman ist ein Spinnenheld mit einem leckeren Schwanz',
'image' => 'www.google.de/info.png'
)
);
?>
So this is basicly the Json code to get it in my app, I hope this is right. If not please help me out with the right json code.
The error I get is following:
06-29 18:03:47.292 5249-5249/? I/art: Not late-enabling -Xcheck:jni (already on)
06-29 18:03:47.293 5249-5249/? W/art: Unexpected CPU variant for X86 using defaults: x86
06-29 18:03:47.714 5249-5249/de.example.kevin.superheroes W/System: ClassLoader referenced unknown path: /data/app/de.example.kevin.superheroes-2/lib/x86
06-29 18:03:47.764 5249-5249/de.example.kevin.superheroes I/InstantRun: starting instant run server: is main process
06-29 18:03:47.954 5249-5249/de.example.kevin.superheroes W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-29 18:03:48.574 5249-5287/de.example.kevin.superheroes D/NetworkSecurityConfig: No Network Security Config specified, using platform default
06-29 18:03:48.639 5249-5285/de.example.kevin.superheroes I/OpenGLRenderer: Initialized EGL, version 1.4
06-29 18:03:48.639 5249-5285/de.example.kevin.superheroes D/OpenGLRenderer: Swap behavior 1
06-29 18:03:48.647 5249-5285/de.example.kevin.superheroes W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
06-29 18:03:48.647 5249-5285/de.example.kevin.superheroes D/OpenGLRenderer: Swap behavior 0
06-29 18:03:48.949 5249-5249/de.example.kevin.superheroes E/RecyclerView: No adapter attached; skipping layout
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: org.json.JSONException: End of input at character 0 of
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONObject.<init>(JSONObject.java:156)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at de.example.kevin.superheroes.MainActivity$1.onResponse(MainActivity.java:60)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at de.example.kevin.superheroes.MainActivity$1.onResponse(MainActivity.java:55)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.os.Looper.loop(Looper.java:154)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at java.lang.reflect.Method.invoke(Native Method)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
06-29 18:03:49.240 5249-5249/de.example.kevin.superheroes W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
The MainActivity:
package de.example.kevin.superheroes;
import android.app.LauncherActivity;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView = null;
private RecyclerView.Adapter adapter = null;
private List<ListItem> listItems = null;
private static final String URL_DATA = "http://192.168.178.29/android/data.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_layout);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Content is loading ...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("Heroes");
for(int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("name"),
o.getString("about"),
o.getString("image")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
ListItem.java
package de.example.kevin.superheroes;
import android.widget.ImageView;
public class ListItem {
public ListItem(String img_url, String head, String desc) {
this.img_url = img_url;
this.head = head;
this.desc = desc;
}
private String img_url = null;
private String head = null;
private String desc = null;
public String getImg_url() {
return img_url;
}
public String getHead() {
return head;
}
public String getDesc() {
return desc;
}
}
MyAdapter
package de.example.kevin.superheroes;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems = null;
private Context context = null;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewHead.setText(listItem.getHead());
holder.textViewDesc.setText(listItem.getDesc());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewHead = null;
public TextView textViewDesc = null;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
}
I would be so glad if you can help me !
If you have any question please ask.
Thanks
After editing my json code I get following error:
PHP
<?php
$json2 = array(
"error" => "false",
"Heroes" => array(
'name' => 'Spiderman',
'about' => 'Spiderman ist ein Spinnenheld mit einem ',
'image' => 'www.google.de/info.png'
)
);
echo json_encode($json2);
?>
No I get this huge errors :
I have postet it on pastebin because its to big for here:
https://pastebin.com/RAuNfZGm
Since it says, "org.json.JSONException: End of input at character 0". It essentially means that you are not returning anything from your php. Like Vaibhav said, you need to encode your array in json using json_encode() and echo the result.
Further Answer
You would need,
<?php
class Hero {
// Creating some properties
public $name;
public $about;
public $image;
// Assigning the values
public function __construct($name, $about, $image) {
$this->name = $name;
$this->about = $about;
$this->image = $image;
}
}
$array_heros[0] = new Hero('Spiderman', 'Spiderman-about', 'image_link');
$array_heros[1] = new Hero('Batman', 'Batman-about', 'image_link');
$json2 = array(
"error" => "false",
"Heroes" => $array_heros
);
echo json_encode($json2);
?>
In you php file its just creating array not json
to create json and return it use last line.
`
<?php
$json2 = array(
"error" => "false",
"Heroes" => array(
'name' => 'Spiderman',
'about' => 'Spiderman ist ein Spinnenheld mit einem leckeren Schwanz',
'image' => 'www.google.de/info.png'
)
);
echo json_encode($json2);
?>`

Android display SD card files throws java.lang.NullPointerException

This is the MainActivity file. When I run it in the emulator and phone, logcat displays a crash due to a NullPointerException. I've read a lot about not letting the user or another activity pass "null" value to my method but could not get around this.
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I used a listview with id= "filelist" in layout
ListView lv;
ArrayList<String> FilesInFolder;
FilesInFolder = GetFiles(Environment.getExternalStorageDirectory().getPath()+ "/sdcard/");
lv = (ListView)findViewById(R.id.filelist);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
This is the logcat:
07-02 01:09:40.500 4407-4407/com.amenhotep.filelister W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
07-02 01:09:40.501 4407-4407/com.amenhotep.filelister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amenhotep.filelister, PID: 4407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amenhotep.filelister/com.amenhotep.filelister.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.amenhotep.filelister.MainActivity.GetFiles(MainActivity.java:44)
at com.amenhotep.filelister.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
the problem is in your sdcard path, use this code to get path of sdcard
String DIR_SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
and there is no need to add "/sdcard/" to it, also change your GetFiles method, and remove mkdirs() because sdcard exists before.
look at this example
File sdcard_files_and_folders[] = new File(DIR_SDCARD).listFiles();
for (File fileOrFolder: sdcard_files_and_folders) {
// do any thing that you want, add them to list or...
Log.i("FILE", fileOrFolder.toString());
}

How to list all events on list view with database?

The program/apk need to list all titles , but when i run it apk close please help me i dont know what happens really
package com.eu.agendamarinhagrande;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
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.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.eu.agendamarinhagrande.JSONParser;
import com.eu.agendamarinhagrande.R;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> empresaList;
// url to get all products list
private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";
// JSON Node names
private static final String TAG_TITULO = "Titulo";
// products JSONArray
String resultado = null;
ListView lista;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap para el ListView
empresaList = new ArrayList<HashMap<String, String>>();
LoadAllProducts loadAllProducts = new LoadAllProducts();
// Cargar los productos en el Background Thread
lista = (ListView) findViewById(R.id.agenda);
loadAllProducts.execute(String.valueOf(lista));
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}//fin onCreate
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Antes de empezar el background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("A carregar eventos. Por favor espere...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* obteniendo todos los productos
*/
protected String doInBackground(String... args) {
// Building Parameters
List params = new ArrayList();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_empresas, "GET", params);
StringBuilder sb = new StringBuilder();
// Check your log cat for JSON reponse
Log.d("All Products: ", url_all_empresas.toString());
resultado = sb.toString();
try {
// Checking for SUCCESS TAG
// products found
// Getting Array of Products
JSONArray arrayJson = new JSONArray(resultado);
for (int i = 0; i<arrayJson.length();i++){
// Storing each json item in variable
JSONObject c = arrayJson.getJSONObject(i);
String Titulo = c.getString(TAG_TITULO);
// creating new HashMap
HashMap map = new HashMap();
// adding each child node to HashMap key => value
map.put(TAG_TITULO, Titulo);
empresaList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
empresaList,
R.layout.single_post,
new String[]{
TAG_TITULO
},
new int[]{
R.id.single_post_tv_id
});
// updating listview
//setListAdapter(adapter);
lista.setAdapter(adapter);
}
});
}
}
}
Check this line in your onCreate() method:
loadAllProducts.execute(String.valueOf(lista));
you can not get the string value of a ListView! If you want to get the value of a textView IN the listView, you could add an OnItemClick event to your listView and get the value of the textView in the selected list item like this:
//a variable, you could use from all the methods, that will have as a value the value of the selected TextView
private String selectedValue;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
View view = (View)v.getParent();
TextView textYouNeed = (TextView) view.findViewById(R.id.textViewId);
selectedValue = textYouNeed.getText();
}
and then use this variable in the line I told about above:
loadAllProducts.execute(selectedValue);
06-19 11:07:34.233 13804-13804/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-19 11:07:34.380 13804-13818/com.eu.agendamarinhagrande I/art﹕ Background sticky concurrent mark sweep GC freed 1879(132KB) AllocSpace objects, 0(0B) LOS objects, 11% free, 538KB/605KB, paused 49.704ms total 65.759ms
06-19 11:07:34.380 13804-13804/com.eu.agendamarinhagrande D/AndroidRuntime﹕ Shutting down VM
06-19 11:07:34.380 13804-13804/com.eu.agendamarinhagrande E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.eu.agendamarinhagrande, PID: 13804
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.eu.agendamarinhagrande/com.eu.agendamarinhagrande.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.eu.agendamarinhagrande.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Android Studio can't find Resuorces

This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' 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 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
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)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#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);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception

Categories

Resources