Android Java Adapter, PHP JSON - java

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);
?>`

Related

Whenever Iam not entering anything in EditText the app is crashes [duplicate]

This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 2 years ago.
Iam making a weather app but whenever Iam not entering or entering wrong city name in EditText the app crashes even though I have used try and catch blocks for error handling.The below is the java,xml code and the logs where it is showing a runtime error.
Java
package com.atul.whatstheweather;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView weatherInfo;
public class Content extends AsyncTask<String, Void ,String>
{
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherData = jsonObject.getString("weather");
JSONArray array = new JSONArray(weatherData);
for(int i=0;i<array.length();i++)
{
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
weatherInfo.setText("Weather: "+main+"\n\n"+"Description: "+description);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
weatherInfo = (TextView)findViewById(R.id.textView);
}
public void clicked(View view)
{
Content content = new Content();
content.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=c20cea76c84b519d67d4e6582064db92");
Log.i("clicked","is working");
}
}
In the Logs given below it is showing Runtime error
Run Logs
05/03 17:35:25: Launching app
Cold swapped changes.
$ adb shell am start -n "com.atul.whatstheweather/com.atul.whatstheweather.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18757 on device xiaomi-redmi_note_3-9b51ac51
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
W/ResourceType: No package identifier when getting name for resource number 0x00000000
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
I/InstantRun: Instant Run Runtime started. Android package is com.atul.whatstheweather, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
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
D/AccessibilityManager: current package=com.atul.whatstheweather, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#9df51ef
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce6e4fc
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build : a7823f5, I59a6815413
Build Date : 09/23/16
OpenGL ES Shader Compiler Version: XE031.07.00.00
Local Branch : mybranch22028469
Remote Branch : quic/LA.BR.1.3.3_rb2.26
Remote Branch : NONE
Reconstruct Branch : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
I/clicked: is working
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.atul.whatstheweather, PID: 18757
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:356)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:266)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:60)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
I/Process: Sending signal. PID: 18757 SIG: 9
Application terminated.
App crashes because you are calling Toast in background thread.
Replace your Toast line in catch block Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show(); with :
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
});
Just delete the Toast.makeText

at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)

I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
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.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:353) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful

No image showing on recyclerview with parse server

I'm very new to Android programming but with a little bit knowledge in java programming and I have an issue with connecting my Parse database to my RecyclerView. Nothing appears on the screen when the activity is launch. I have Log all the output query from Parse server and manage to get every rows of "image_url" but it seems to have problem when i try to output the image. I don't understand where the problem comes in and I really need explanation with this.
MainActivity
package sg.com.test.parseandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private GridLayoutManager gridLayoutManager;
private static CustomAdapter adapter;
private List<MyData> data_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
data_list = new ArrayList<>();
gridLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(gridLayoutManager);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject obj : postList) {
MyData data = new MyData(obj.getObjectId(), obj.getString("image_url"));
data_list.add(data);
Log.d("MAINACTIVITY", String.format("objectid- %s", data_list.get(postList.indexOf(obj)).getObjectId()));
}
} else {
Toast.makeText(MainActivity.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
});
adapter = new CustomAdapter(this, data_list);
recyclerView.setAdapter(adapter);
}
}
CustomAdapter.java
package sg.com.test.parseandroid;
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.ImageView;
import com.bumptech.glide.Glide;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<MyData> my_data;
public CustomAdapter(Context context, List<MyData> my_data) {
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Glide.with(context).load(my_data.get(position).getImage_url()).into(holder.imageView);
}
#Override
public int getItemCount() {
return my_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById((R.id.image));
}
}
}
MyData.java
package sg.com.test.parseandroid;
public class MyData {
private String objectId, image_url;
MyData(String objectId, String image_url) {
this.objectId = objectId;
this.image_url = image_url;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
}
Logcat
02-14 19:22:29.157 1728-1728/? I/zygote: Not late-enabling -Xcheck:jni (already on)
02-14 19:22:29.208 1728-1728/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
02-14 19:22:29.523 1728-1728/sg.com.test.parseandroid I/InstantRun: starting instant run server: is main process
02-14 19:22:29.622 1728-1766/sg.com.test.parseandroid D/NetworkSecurityConfig: No Network Security Config specified, using platform default
02-14 19:22:29.933 1728-1773/sg.com.test.parseandroid D/OpenGLRenderer: HWUI GL Pipeline
02-14 19:22:29.984 1728-1773/sg.com.test.parseandroid I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid I/OpenGLRenderer: Initialized EGL, version 1.4
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid D/OpenGLRenderer: Swap behavior 1
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid D/OpenGLRenderer: Swap behavior 0
02-14 19:22:30.001 1728-1773/sg.com.test.parseandroid D/EGL_emulation: eglCreateContext: 0x9ec85420: maj 2 min 0 rcv 2
02-14 19:22:30.021 1728-1773/sg.com.test.parseandroid D/EGL_emulation: eglMakeCurrent: 0x9ec85420: ver 2 0 (tinfo 0x9ec83310)
02-14 19:22:30.078 1728-1773/sg.com.test.parseandroid D/EGL_emulation: eglMakeCurrent: 0x9ec85420: ver 2 0 (tinfo 0x9ec83310)
02-14 19:22:31.231 1728-1728/sg.com.test.parseandroid D/MAINACTIVITY: objectId- caNtpHNOZB
02-14 19:22:31.231 1728-1728/sg.com.test.parseandroid D/MAINACTIVITY: objectId- G5eDwzYS8p
02-14 19:22:31.231 1728-1728/sg.com.test.parseandroid D/MAINACTIVITY: objectId- aap5bR7Xb5
Updates:
Can't get any LOG in CustomAdapter.java
card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="sg.com.test.parseandroid.MainActivity"
android:id="#+id/recycler_view"/>
I will get an error if i Log the data_list
ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject obj : postList) {
MyData data = new MyData(obj.getObjectId(), obj.getString("image_url"));
data_list.add(data);
Log.d("MAINACTIVITY", String.format("objectid- %s", data_list.get(postList.indexOf(obj)).getImage_url()));
}
} else {
Toast.makeText(MainActivity.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
});
MyData data = data_list.get(0);
Log.d("MainActivity.onCreate", data.getObjectId());
adapter = new CustomAdapter(this, data_list);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
Logcat
02-15 05:26:43.820 16722-16722/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.com.creertech.parseandroid, PID: 16722
java.lang.RuntimeException: Unable to start activity ComponentInfo{sg.com.creertech.parseandroid/sg.com.creertech.parseandroid.MainActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at sg.com.creertech.parseandroid.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
At first, insert log inside every fuctions in CustomAdapter and see if the data is reaching here or not. eg.
Log.d("CustomAdapter", "size of data==> "+my_data.size());
If all good then try this code inside onCreateViewHolder(). Instead of parent, false try null. This may help
View view = LayoutInflater.from(context.inflate(R.layout.card, null);
Also can you show the card.xml layout??

Capture, store and retrieve photo in activity

I have a problem, that I can't fix. I have spent almost all day today trying to get this to work, but I can't and I am out of any ideas, so decided to ask for your help.
Also, I have looked around google and stackoverflow for answers, none of which helped me.
The problem regards photo capturing with android. I have an activity, where I can "create" a new item that is later on stored in a database. I can pass it a name and location, as well as take a photo that binds to it. When I press "add" it is saved to the database. Everything works, except the Camera intent. I want to be able to take a photo in that activity, that binds to the "object" I'm creating, so later on I can view that photo when I click on a particular "object" on a list. I do have permissions (write and read) in my AndroidManifest, but still they dont help.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
<uses-feature android:name="android.hardware.camera"
android:required="false"
/>
My android version is 6.0.
This code is the most recent compilation of solutions that I have gathered to try to make it work. I would very much appreciate your help with my issue.
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class CreateItemFragment extends Fragment {
private static final int REQUEST_PHOTO = 2;
private static final String TAG = "button clicked";
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private TextView mNameText;
private TextView mLocationText;
private Button mAddButton;
private ImageButton mPhotoButton;
private ImageView mPhotoView;
private String mCurrentPhotoPath;
private File mPhotoFile;
private Item mItem;
private List<Item> mItems;
private static ItemStash sItemStash;
public static CreateItemFragment newInstance(){
return new CreateItemFragment();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_create_item, container, false);
mNameText = (TextView)view.findViewById(R.id.item_name);
mLocationText = (TextView)view.findViewById(R.id.item_location);
sItemStash = sItemStash.get(getContext());
mAddButton = (Button)view.findViewById(R.id.add_button);
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mNameText.getText().length() > 0 && mLocationText.getText().length() > 0){
sItemStash.addItem(
new Item(mNameText.getText().toString(),
mLocationText.getText().toString()));
Toast.makeText(getActivity(), mNameText.getText().toString() + " added to the list!", Toast.LENGTH_SHORT).show();
}
mNameText.setText("");
mLocationText.setText("");
}
});
mPhotoButton = (ImageButton)view.findViewById(R.id.photo_button);
//final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*
PackageManager packageManager = getActivity().getPackageManager();
boolean canTakePhoto = mPhotoFile != null && captureImage.resolveActivity(packageManager) != null;
mPhotoButton.setEnabled(canTakePhoto);
if(canTakePhoto) {
Uri uri = Uri.fromFile(mPhotoFile);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
*/
mPhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifyStoragePermissions(getActivity());
capturePhotoIntent();
//startActivityForResult(captureImage, REQUEST_PHOTO);
//mPhotoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
//mPhotoFile = new File(mItem.setPhotoFilename(mNameText.getText().toString()));
}
});
mPhotoView = (ImageView)view.findViewById(R.id.item_photo);
//updatePhotoView();
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_PHOTO && resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap)extras.get("data");
//mPhotoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
mPhotoView.setImageBitmap(imageBitmap);
}
}
/*
private void updatePhotoView(){
if(mPhotoFile == null || !mPhotoFile.exists()){
Log.d(TAG, "is clicked");
mPhotoView.setImageDrawable(null);
}else{
Bitmap bitmap = PhotoUtils.getScaledBitmap(mPhotoFile.getPath(), getActivity());
mPhotoView.setImageBitmap(bitmap);
}
}
*/
private void capturePhotoIntent(){
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = getActivity().getPackageManager();
if(photoIntent.resolveActivity(packageManager) != null){
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ioe){
ioe.printStackTrace();
}
if(photoFile != null) {
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(photoIntent, REQUEST_PHOTO);
}
}
}
public File createImageFile() throws IOException {
verifyStoragePermissions(getActivity());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
*EDIT
Forgot to paste in my stack trace. I do get this:
04-21 22:34:56.688 3574-3604/com.bignerdranch.android.tingleapp
W/OpenGLRenderer: Fail to change FontRenderer cache size, it already initialized
04-21 22:34:56.704 3574-3574/com.bignerdranch.android.tingleapp D/android.widget.GridLayout: horizontal constraints: x1-x0>=163, x2-x1>=1080, x2-x0<=1080 are inconsistent; permanently removing: x2-x0<=1080.
04-21 22:34:56.708 3574-3574/com.bignerdranch.android.tingleapp D/android.widget.GridLayout: vertical constraints: y2-y0>=745, y2-y1<=136, y1-y0<=136 are inconsistent; permanently removing: y2-y1<=136.
04-21 22:34:56.819 3574-3604/com.bignerdranch.android.tingleapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8767340
04-21 22:34:57.533 3574-3574/com.bignerdranch.android.tingleapp W/System.err: java.io.IOException: open failed: EACCES (Permission denied)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createNewFile(File.java:939)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createTempFile(File.java:1004)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.createImageFile(CreateItemFragment.java:173)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.capturePhotoIntent(CreateItemFragment.java:154)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.access$300(CreateItemFragment.java:30)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment$2.onClick(CreateItemFragment.java:108)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.view.View.performClick(View.java:5226)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.view.View$PerformClick.run(View.java:21266)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Looper.loop(Looper.java:168)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5845)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at libcore.io.Posix.open(Native Method)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createNewFile(File.java:932)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: ... 14 more
the method verisfyStoragePermission() was supposed to fix that error as I found in other topics, but I still get this error

From json file to String[]

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.

Categories

Resources